Posted on Oct 31, 2019

You have already seen you can use + operator for adding numbers and at the same time to concatenate strings. It is possible because + operator is overloaded by both int class and str class. The operators are actually methods defined in respective classes. Defining methods for operators is known as operator overloading. For e.g: To use + operator with custom objects  you need to define a method called __add__.

Let's take an example to understand better

Expected Output:

 1 2 3 4 5 9
import math

class Circle:

def area(self):
return math.pi * self.__radius ** 2

c1 = Circle(4)

c2 = Circle(5)

c3 = c1 + c2 # This became possible because we have overloaded + operator by adding a    method named __add__

In the above example we have added __add__()  method which allows use to use the + operator to add two circle objects. Inside the __add__()  method we are creating a new object and returning it to the caller.

Python has many other special methods like __add__(), see the list below.

Operator Function   Method Description
*  __mul__(self, other)  Multiplication
- __sub__(self, other)  Subtraction
% __mod__(self, other)  Remainder
/ __truediv__(self, other)  Division
< __lt__(self, other)  Less than
<= __le__(self, other) , Less than or equal to
==   __eq__(self, other) , Equal to
!=   __ne__(self, other) , Not equal to
>  __gt__(self, other)  , Greater than

>=,  __ge__(self, other) , Greater than or equal to [index] ,  __getitem__(self, index) , Index operator in ,  __contains__(self, value) , Check membership len , __len__(self) ,  The number of elements str , __str__(self) ,  The string representation

Program below is using some of the above mentioned functions to overload operators.

Expected Output:

 1 2 3 4 5 6 4 5 9 True True Circle with radius 9
import math

class Circle:

def area(self):
return math.pi * self.__radius ** 2

def __gt__(self, another_circle):

def __lt__(self, another_circle):

def __str__(self):

c1 = Circle(4)

c2 = Circle(5)

c3 = c1 + c2