Operator Overloading in Python

Posted by Afsal on 26-Aug-2022

Hello Pythonistas!

Today we are going to learn about operator overloading in Python. We know that in Python most operators are overloaded, for example, + operator can be used to add two strings, two lists, two numbers, etc.

Code

>>> 1+1
2
>>> "a" + "b"
'ab'
>>> [1, 2, 3] + [4, 4, 5]
[1, 2, 3, 4, 4, 5]
>>>

In a previous post about underscore meaning in Python. We have mentioned python there are some dunder methods or magic methods. One of the dunder methods is called __add__ by overriding this method we can overload + operator.

We can create a new class called WierdInt. Here + operator returns the difference between the numbers. Let us dive into the code

Code

class WierdInt:
    def __init__(self, number):
        self.number = number

    def __str__(self):
        return f"{self.number}"

a = WierdInt(10)
print(a)
b = WierdInt(5)
print(b)
c = a + b

Output

10
5
Traceback (most recent call last):
  File "operator_overloading.py", line 17, in <module>
    c = a + b
TypeError: unsupported operand type(s) for +: 'WierdInt' and 'WierdInt'

Why

For this class WierdInt, there is no __add__ written for this class. Now we can overload + operator. 

Code

class WierdInt:
    def __init__(self, number):
        self.number = number

    def __str__(self):
        return f"{self.number}"

    def __add__(self, other):
        return self.number - other.number

a = WierdInt(10)
print(a)
b = WierdInt(5)
print(b)
c = a + b
print(c)

Output

10
5
5

Here in this example, a + b returns the difference between 2 numbers. Similarly using these dunder methods we can overload any operators easily. To learn more about this you can refer to the Python official documentation

Hope you have learned something from this post. Please share your valuable suggestion and feedback with afsal@parseltongue.co.in