Python Operator Overloading

We know that an operator is a symbol that performs some action. For example, '+' is an operator that performs addition operation when used on numbers. When an operator can perform different actions, it is said to exhibit polymorphism.


A Python program to use addition operator to act on different types of objects.


A Python program to use addition operator to add the contents of two objects.


We can overload the '+' operator to act upon the two objects and perform addition operation on the contents of the objects. That means we are giving additional task to the '+' operator.


A Python program to overload the addition operator (+) to make it act on class objects.


Following Table summarizes important operators and their corresponding internal methods that can be overridden to act on objects. These methods are called magic methods.


Operator Magic method
+ object._add_(self,other)
- object._sub_(self,other)
* object._mul_(self,other)
/ object._div_(self,other)
// object._floordiv_(self,other)
% object._mod_(self,other)
** object._pow_(self,other[,modulo])
+= object._iadd_(self,other)
-= object._isub_(self,other)
*=() object._imul_(self,other)
/= object._idiv_(self,other)
//= object._ifloordiv_(self,other)
%= object._imod_(self,other[,modulo])
**= object._ipow_(self,other)
< object._lt_(self,other)
<= object._le_(self,other)
> object._gt_(self,other)
>= object._ge_(self,other)
== object._eq_(self,other)
!= object._ne_(self,other)

If we want to overload the greater than (>) operator. For this purpose the magic method __gt__() should be overridden. For example,

def __gt__(self, other):

return self.pages>other.pages


A Python program to overload greater than (>) operator to make it act on class objects.


A Python program to overload the multiplication (*) operator to make it act on objects.