Operator Overloading
Learn about the usability of operator overloading in Python.
We'll cover the following...
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 = rself.__imag = idef __add__(self, other) :z = Complex( )z.__real = self.__real + other.__realz.__imag = self.__imag + other.__imagreturn zdef __sub__(self, other) :z = Complex( )z.__real = self.__real - other.__realz.__imag = self.__imag - other.__imagreturn zdef __iadd__(self, other) :z = Complex( )z.__real = self.__real + other.__realz.__imag = self.__imag + other.__imagreturn zdef __eq__(self, other):real = self.__real == other.__realimag = self.__imag == other.__imagreturn (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 + c2c3.display( )c4 = c1 - c2c4.display( )c1 = Complex(1.1, 0.2)c2 = Complex(1.1, 0.2)c1 += c2c1.display( )if c3 == c1:print('Both complex numbers are equal.')
...