Python Operator Overloading

  • Python

In this tutorial, we’ll learn about what is operator overloading in Python, where to use it and how to use it.

We already know what operators are like addition operator(+), subtraction(-), etc. Let’s take an example of + operator.

x = 3
y = 7

print(x + y)

We know that it will print output as 10 but do you know what is being performed in the background? We know that x and y are of type int and int is a class. Since a class has some methods, here int is also calling the add method. Let’s check the below code.

x = 3
y = 7

print(int.__add__(x,y))
print(x + y)

Output :

10
10

Just like add method, there are multiple methods in int class. Similarly, if you want to subtract, it will call __sub__() method and these are called Magic Methods.

Let’s understand Operator Overloading now.

We’ll now define two classes where we will perform addition of scores of two participants in two events.

class Comp:
  def __init__(self, score1, score2):
    self.score1 = score1
    self.score2 = score2

p1 = Comp(6,8)
p2 = Comp(9,6)

result = p1 + p2

Output :

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    result = p1 + p2
TypeError: unsupported operand type(s) for +: 'Comp' and 'Comp'

Oops! We got an error. But why? We tried to add the score of two participants using the + operator.

In the background, python should call the __add__() method but the reason it did not call it is the class object did not know that and we’ll need to manually define it.

class Comp:
  def __init__(self, score1, score2):
    self.score1 = score1
    self.score2 = score2

  def __add__(self, other):
    score1 = self.score1 + other.score1
    score2 = self.score2 + other.score2
    result = Comp(score1,score2)
    return result
    

p1 = Comp(6,8)
p2 = Comp(9,6)

result = p1 + p2
print(result.score1)

Output :

15

In order to add two Comp or two classes, we need to overload the + operator because int, string, etc knows + but the class object does not which is why we needed to define the add method. This can also be performed on other operators like subtraction, multiplication, and comparison operator too.

The above action is known as Operator Overloading in Python.