Python Operator Overloading

In this article, you’ll learn about python operator overloading 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:

a = 10
b = 20
print (a+b)

Output:

30

a = "hello "
b = "programmer"
print(a+b)

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:

Operators Methods
+ __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:

#without  operator overloading
class Test:  
  def __init__(self, value):
    self.value = value

n1 = Test(20)
n2 = Test(10)
print (n1 + n2)

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:

#with operator overloading
class Test:
  def __init__(self, value):
    self.value = value
   
  def  __add__(self, other):
    return (self.value + other.value)
   
n1 = Test(5)
n2 = Test(6)
print (n1 + n2)

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.

2 thoughts on “Python Operator Overloading”

Leave a Comment

Your email address will not be published. Required fields are marked *