Course Content
Python Programming Tutorial
About Lesson

Operator overloading in Python

Operators are used in Python to perform specific operations on the given operands. The operation that any particular operator will perform on any predefined data type is already defined in Python.

Each operator can be used in a different way for different types of operands. For example, + operator is used for adding two integers to give an integer as a result but when we use it with float operands, then the result is a float value and when + is used with string operands then it concatenates the two operands provided.

This different behaviour of a single operator for different types of operands is called Operator Overloading. The use of + operator with different types of operands is shown below:

>>> x=10
>>> y=20
>>> x+y
30

>>> z=10.4
>>> x+z
20.4

>>> s1 = 'hello '
>>> s2 = 'world'
>>> s1+s2
'hello world'
 

Can + Operator Add anything?

The answer is No, it cannot. Can you use the + operator to add two objects of a class. The + operator can add two integer values, two float values or can be used to concatenate two strings only because these behaviours have been defined in python.

So if you want to use the same operator to add two objects of some user defined class then you will have to defined that behaviour yourself and inform python about that.

If you are still not clear, let’s create a class and try to use the + operator to add two objects of that class,

class Complex:
    def __init__(self, r, i):
        self.real = r
        self.img = i

c1 = Complex(5,3)
c2 = Complex(2,4)
print("sum = ", c1+c2)
 

Traceback (most recent call last): File “/tmp/sessions/1dfbe78bb701d99d/main.py”, line 7, in print(“sum = “, c1+c2) TypeError: unsupported operand type(s) for +: ‘Complex’ and ‘Complex’

 

So we can see that the + operator is not supported in a user-defined class. But we can do the same by overloading the + operator for our class Complex. But how can we do that?


Special Functions in Python

Special functions in python are the functions which are used to perform special tasks. These special functions have __ as prefix and suffix to their name as we see in __init__() method which is also a special function. Some special functions used for overloading the operators are shown below:

Mathematical Operator

Below we have the names of the special functions to overload the mathematical operators in python.

Name Symbol Special Function
Addition + __add__(self, other)
Subtraction - __sub__(self, other)
Division / __truediv__(self, other)
Floor Division // __floordiv__(self, other)
Modulus(or Remainder) % __mod__(self, other)
Power ** __pow__(self, other)

Assignment Operator

Below we have the names of the special functions to overload the assignment operators in python.

Name Symbol Special Function
Increment += __iadd__(self, other)
Decrement -= __isub__(self, other)
Product *= __imul__(self, other)
Division /= __idiv__(self, other)
Modulus %= __imod__(self, other)
Power **= __ipow__(self, other)

Relational Operator

Below we have the names of the special functions to overload the relational operators in python.

Name Symbol Special Function
Less than < __lt__(self, other)
Greater than > __gt__(self, other)
Equal to == __eq__(self, other)
Not equal != __ne__(self, other)
Less than or equal to <= __le__(self, other)
Greater than or equal to > = __gt__(self, other)

It’s time to see a few code examples where we actually use the above specified special functions and overload some operators.


Overloading + operator

In the below code example we will overload the + operator for our class Complex,

 
 
class Complex:
    # defining init method for class
    def __init__(self, r, i):
        self.real = r
        self.img = i

    # overloading the add operator using special function
    def __add__(self, sec):
        r = self.real + sec.real
        i = self.img + sec.img
        return complx(r,i)

    # string function to print object of Complex class
    def __str__(self):
        return str(self.real)+' + '+str(self.img)+'i'

c1 = Complex(5,3)
c2 = Complex(2,4)
print("sum = ",c1+c2)
 

sum = 7 + 7i

In the program above, __add__() is used to overload the + operator i.e. when + operator is used with two Complex class objects then the function __add__() is called.

__str__() is another special function which is used to provide a format of the object that is suitable for printing.


Overloading < operator

Now let’s overload the less than operator so that we can easily compare two Complex class object’s values by using the less than operaton <.

As we know now, for doing so, we have to define the __lt__ special function in our class.

Based on your requirement of comparing the class object, you can define the logic for the special functions for overriding an operator. In the code above, we have given precedence to the real part of the complex number, if that is less then the whole complex number is less, if that is equal then we check for the imaginary part.

Conclusion

Overloading operators is easy in python using the special functions and is less confusion too.

error: Content is protected !!