Operator overloading in Python | FACE Prep

Operator overloading in Python is the ability of a single operator to perform more than one operation based on the class (type) of operands.

For example, the + operator can be used to add two numbers, concatenate two strings or merge two lists. This is possible because the + operator is overloaded with int and str classes. Similarly, you can define additional methods for these operators to extend their functionality to various new classes and this process is called Operator overloading.

Why Do We Need To Overload Operators?

Let us assume we have an object called string1 which is a string object as defined below. Now, when we try to add a string to this string object, the compiler will throw an error. This is because the compiler doesn’t know how to add them. Have a look at what happens when executed.

Note: You will understand the below code completely by the end of this article.

# declare our own string class
class String:

          # magic method to initiate object
          def __init__(self, string):
                     self.string = string                   
          # print our string object
          def __repr__(self):
                     return 'Object: {}'.format(self.string)

# Driver Code
if __name__ == '__main__': 

          # object creation
          string1 = String('Hello')         
          # concatenate String object and a string
          print(string1 +' world')
Output: 
TypeError: unsupported operand type( s ) for +: ‘String’ and ‘str’

This error can be avoided by adding the   __ add__  method to the String class. This way, we are overaloding the + operator to concatenate a string object with a string.

# declare our own string class
class String:     

          # magic method to initiate object
          def __init__(self, string):
                     self.string = string                   
          # print our string object
          def __repr__(self):
                     return 'Object: {}'.format(self.string)                    
          def __add__(self, other):
                     return self.string + other

# Driver Code
if __name__ == '__main__':

          # object creation
          string1 = String('Hello')         
          # concatenate String object and a string
          print(string1 +' World')
Output: Hello World

How To Overload Operators In Python?

In Python, when any operator is used, a special function is internally invoked by the compiler for that particular operator. Python methods that have double underscores before and after their names are called Magic methods or Special functions. By changing this magic method’s code, we can extend the functionality of the operator.

For example, when we use -= operator, the magic or special method __isub__  is invoked by the compiler.

Python Magic Methods for Operator Overloading

a) Arithmetic Operators

OperatorSpecial functions
+__add__(self, other)
__sub__(self, other)
*__mul__(self,other)
/__truediv__(self,other)
//__floordiv__(self,other)
%__mod__(self,other)
**__pow__(self,other)

  
b) Comparison Operators

Operator      Special functions
<__lt__(self,other)
>__gt__(self,other)
<=__le__(self,other)
>=__ge__(self,other)
==__eq__(self,other)
!=__ne__(self,other)


c) Assignment Operators

OperatorSpecial functions
+=__iadd__(self,other)
-=__isub__(self,other)
*=__imul__(self,other)
/=__idiv__(self,other)
//=__ifloor div__(self,other)
%=__imod__(self,other)
**=__ipow__(self,other)


d) Unary Operators

Operator                   Special functions
+__neg__(self,other)
__pos__(self,other)
~__invert__(self,other)

Examples of Operator Overloading in Python

a) Operator overloading using comparison operators

#program to compare the score of two students m1 & m2.
class Student:
          def __init__(self, m1, m2):  #initialization
                     self.m1 = m1
                     self.m2 = m2
          def __add__(self, m1, m2):   #adding the two objects
              m1 = self.m1 + other.m1
              m2 = self.m2 + other.m2
              s3 = student (m1,m2)
              return s3
          def __gt__(self, other):     #comparing the two objects
              r1 = self.m1 + self.m2
              r2 = other.m1 + other.m2
              if(r1 > r2):
                  return True
              else:
                  return False

s1 = Student(65, 85)
s2 = Student(90, 80)
if (s1 > s2):
          print ("S1 wins")
else:
          print ("S2 wins")
Output:
S2 wins

b) Operator overloading using relational & comparison operators  

#Python program to compare two radii
class Circle:
          def __init__(self, a):
                     self.a = a
          def __lt__(self, other):
                     if(self.a<other.a):
                               return 'Radius(r2) is greater'
                     else:
                               return "Radius(r1) is greater"
          def __eq__(self, other):
                     if(self.a == other.a):
                               return "Radius are equal"
                     else:
                               return "Not equal"                                        

r1 = Circle(12)
r2 = Circle(9)
print(r1 < r2)
r3 = Circle(6)
r4 = Circle(4)
print(r3 == r4)
Output:
Radius(r1) is greater
Not equal