...

/

Operator Overloading

Operator Overloading

Learn about the usability of operator overloading in Python.

Common operators are used for their predefined purpose and functionality. When we intend to use them for an additional purpose, we need to explicitly define their behavior for a particular class. This phenomenon is called operator overloading.

Since Complex is a user-defined class, Python doesn’t know how to add objects to this class. We can teach it how to do that by overloading the +, -, +=, and == operators, as shown below:

Press + to interact
class Complex :
def __init__(self, r = 0.0, i = 0.0) :
self.__real = r
self.__imag = i
def __add__(self, other) :
z = Complex( )
z.__real = self.__real + other.__real
z.__imag = self.__imag + other.__imag
return z
def __sub__(self, other) :
z = Complex( )
z.__real = self.__real - other.__real
z.__imag = self.__imag - other.__imag
return z
def __iadd__(self, other) :
z = Complex( )
z.__real = self.__real + other.__real
z.__imag = self.__imag + other.__imag
return z
def __eq__(self, other):
real = self.__real == other.__real
imag = self.__imag == other.__imag
return (real == True & imag == True)
def display(self) :
print(self.__real, self.__imag)
c1 = Complex(1.1, 0.2)
c2 = Complex(1.1, 0.2)
c3 = c1 + c2
c3.display( )
c4 = c1 - c2
c4.display( )
c1 = Complex(1.1, 0.2)
c2 = Complex(1.1, 0.2)
c1 += c2
c1.display( )
if c3 == c1:
print('Both complex numbers are equal.')
...