Search⌘ K
AI Features

Operator Overloading

Explore how to define custom behaviors for common operators in Python classes through operator overloading. Learn to implement special methods such as __add__, __sub__, and __eq__ to enable intuitive operations on objects. Understand the list of overloadable operators and the unique aspect that Python does not support function overloading.

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:

Python 3.8
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.')
...