Operator Overloading in Python

In this article, we’ll learn about operator overloading in Python with examples.

We all know what are operators (+, -, <=). In python, operators work for built in classes, but some operator behaves differently with different types. For example ‘+’ operator can add two numbers and also can concatenate two strings.

Program:

Output:

30

Program:

 

Output:

hello programmer”

 

So, using any operator to perform different operation that are not usually performed, is known as operator overloading. We can change the behavior of operators using operator overloading.

Or we can also say that “assigning a different work to an operator is known as operator overloading”.

To perform operator overloading, there are some magic methods provided by Python. Using these methods we can perform any operation we want on a operator.

The operators that can be overloaded are as follows:

OperatorsMethods
+__add__(self, other)
__sub__(self, other)
*__mul__(self, other)
//__floordiv__(self, other)
/__div__(self, other)
%__mod__(self, other)
**__pow__(self, other[ , modulo])
<__lt__(self, other)
<=__le__(self, other)
==__eq__(self, other)
!=__ne__(self , other)
>=__ge__(self, other)

The basic idea to perform the operator overloading in python is to define any of these methods in the class then call them using operators.

Let’s see an example. Suppose we want to overload  ‘+’ operator.

As mentioned above that we can concatenate two strings and add two numbers with the help of ‘+’ operator but here we’ll perform the addition on two objects of a class named as Test.

 

Program:

Output:

TypeError: unsupported operand type(s) for +: ‘Test’ and ‘Test’

So there is an error that says that we can’t perform addition to add values of the both the Test class’s objects. So we will define the __add___(self, other)  method  here to add the values of both the objects.

Program:

 

Output:

11

So what we did in above program is just added a __add__(self, other) method that will be called when we use ‘+’ operator on the objects of the Test class.

It is not necessary to always perform addition on ‘+’ operator we can do anything we want like we can also subtract object’s values by using operator ‘+’.

In this way you can achieve operator overloading in python. Comment below if you have any doubts.