Operator Overloading
What is Operator Overloading:
Operator overloading in Python refers to the ability to define how operators behave for custom classes. By overloading operators, you can specify custom behavior for operations like addition, subtraction, multiplication, and more when applied to objects of your class.
Python provides special methods, also known as magic methods or dunder methods, that you can implement in your class to enable operator overloading. These methods are identified by their double underscore (dunder) prefix and suffix names.
In Python, the operator overloading methods __add__, __sub__, and __mul__ are specifically designed to handle addition, subtraction, and multiplication operations, respectively. These methods are part of the Python data model and are recognized by the interpreter to perform corresponding operations when objects are used with the +, -, and * operators.
If you want to overload other operators or define custom behavior for different operators, you need to use the appropriate dunder methods for those operators. For example, for division, you would use __truediv__ or __floordiv__ for true division or floor division, respectively.
Attempting to use other names for operator overloading methods will not work as expected because the interpreter will not recognize those methods as operators, and they will not be invoked automatically when the corresponding operators are used.
For example, if you want to overload the addition operator (+) for a custom class MyClass, you would define the __add__ method in the class. When you use the + operator with instances of MyClass, Python internally calls the __add__ method to perform the addition operation.
For example,
class MyClass:
def __init__(self, value):
self.value = value
def __add__(self, other):
return MyClass(self.value + other.value)
# Example usage
obj1 = MyClass(5)
obj2 = MyClass(10)
result = obj1 + obj2 # Calls obj1.__add__(obj2)
print(result.value) #
Output: 15
Explanation:
In this example, the __add__ method defines how the addition operator + behaves when applied to instances of MyClass. When obj1 + obj2 is executed, Python internally calls obj1.__add__(obj2), which returns a new instance of MyClass with the sum of the values.
By implementing specific dunder methods in your class, you can customize the behavior of various operators, allowing your objects to interact with Python's built-in operators in a way that makes sense for your application.
User Input:
class MyClass:
def __init__(self, value):
self.value = value
def __add__(self, other):
return MyClass(self.value + other.value)
# Function to get user input for creating MyClass instances
def get_user_input():
value = int(input("Enter a value: "))
return MyClass(value)
# Get user input for obj1 and obj2
print("Enter values for obj1:")
obj1 = get_user_input()
print("Enter values for obj2:")
obj2 = get_user_input()
# Perform addition using the + operator
result = obj1 + obj2 # Calls obj1.__add__(obj2)
print("__________________")
# Print the result
print("Result of addition:", result.value)
Arithmetic Operators:
1. Addition '+' Operator Overloading:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
# Example usage
v1 = Vector(1, 2)
v2 = Vector(3, 4)
result = v1 + v2
print("Result of addition:", (result.x, result.y)) # Output: (4, 6)
2. Subtraction ‘ –‘:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
# Example usage
v1 = Vector(5, 5)
v2 = Vector(2, 2)
result = v1 - v2
print("Result of subtraction:", (result.x, result.y)) # Output: (3, 3)
3. Multiplication ‘*’ :
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
# Example usage
v = Vector(3, 4)
result = v * 2
print("Result of multiplication:", (result.x, result.y)) # Output: (6, 8)
4. Division ‘/:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __truediv__(self, scalar):
return Vector(self.x / scalar, self.y / scalar)
# Example usage
v = Vector(6, 8)
result = v / 2
print("Result of division:", (result.x, result.y)) # Output: (3.0, 4.0)
Floor Division ‘//’:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __floordiv__(self, scalar):
return Vector(self.x // scalar, self.y // scalar)
# Example usage
v = Vector(6, 8)
result = v // 2
print("Result of floor division:", (result.x, result.y)) # Output: (3, 4)
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏