Awesome Operator Overloading in Python #PyTip04

Vivek K. Singh
2 min readOct 17, 2022

--

In Python, Operator Overloading can be easily done using the available dunder methods on any class.

In the following article you will learn how you can add support to Operator in Python.

Problem

You are creating a class of complex numbers, you want to add a functionality by which real and imaginary numbers can be added.

class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __repr__(self):
return f"{self.real} + {self.imaginary}i"

Running the above in interactive mode results in:

>>> c1 = Complex(2,3)
>>> c2 = Complex(6,9)
>>> c1
2 + 3i
>>> c2
6 + 9i
>>> c1 + c2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'Complex' and 'Complex'

In the above program you can see that c1 and c2 cannot be added. To support addition we have to implement the __add__ method in our class.

Solution

class Complex:
# previous lines hidden
def __add__(self, other):
return (Complex(self.real+other.real, self.imaginary +
other.imaginary))

After adding the dunder method we can run this program in terminal as:

>>> c1 = Complex(2,3)
>>> c2 = Complex(6,9)
>>> c1 + c2
8 + 12i

You can see that now addition works fine in out Complex class. You can also add support to other operators using the built-in dunder methods in Python.

A full list of supported operators can be found here.

Hope you liked this article, support by following and sharing.

--

--

Vivek K. Singh
Vivek K. Singh

Written by Vivek K. Singh

Python Programmer. Creating content around Python and Web Development https://linktr.ee/vivekthedev

No responses yet