Python program to overload (addition of objects) Operator Overloading

8/6/2022
All Articles

#Python program to overload (addition of objects) Operator Overloading #program #python #overloading #example

Python program to overload (addition of objects)  Operator Overloading

Python program to overload (addition of objects)  Operator Overloading 

Python has some special function or magic function that is automatically called when it is associated with that particular operator..By implementing a specific method called __add__, you can overload Python's addition operator (+) for objects of a custom class. Here is a straightforward illustration of operator overloading in addition:

class complex:
    def __init__(self, a, b):
        self.a = a
        self.b = b
  
     # adding two objects 
    def __add__(self, other):
        return self.a + other.a, self.b + other.b
  
Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)

When you run this program, it will create two complex Number objects, add them using the + operator, and display the result:

Result : (3, 5)

Conclusion

This demonstrates operator overloading for the addition operator in Python program. You can customize the behavior of other operators for example subtraction, multiplication, division) in a similar way by defining the corresponding special methods

Article