Python program to overload (addition of objects) Operator Overloading
#Python program to overload (addition of objects) Operator Overloading #program #python #overloading #example
Python provides a powerful feature called operator overloading, which allows you to define custom behavior for built-in operators when applied to user-defined objects. This is achieved using special methods, also known as magic methods.
One such method is __add__
, which enables overloading of the +
(addition) operator. By implementing this method in a class, we can define how objects of that class should be added together.
When the +
operator is used between objects of a user-defined class, Python invokes the __add__
method defined within that class. Below is a Python program demonstrating the overloading of the addition operator (+
) for objects of a custom class representing complex numbers.
+
Operator in Python# Class representing a complex number
class Complex:
def __init__(self, a, b):
self.a = a # Real part
self.b = b # Imaginary part
# Overloading the + operator
def __add__(self, other):
return Complex(self.a + other.a, self.b + other.b)
# Display function for output formatting
def __str__(self):
return f"({self.a} + {self.b}i)"
# Creating complex number objects
Ob1 = Complex(1, 2)
Ob2 = Complex(2, 3)
Ob3 = Ob1 + Ob2 # Using overloaded + operator
print("Result of Addition:", Ob3) # Output: (3 + 5i)
Complex
class has an __init__
method that initializes the real (a
) and imaginary (b
) parts of the complex number.__add__
method is implemented to handle addition between two Complex
objects.Ob1 + Ob2
is executed, Python calls Ob1.__add__(Ob2)
, which returns a new Complex
object with the summed values.__str__
method is used to format the output.Result of Addition: (3 + 5i)
This example demonstrates how operator overloading can be used to redefine the behavior of the +
operator for custom objects. Similarly, you can overload other operators such as -
, *
, /
, and %
by defining their respective magic methods (__sub__
, __mul__
, __truediv__
, __mod__
, etc.).