Skip to content

What is Operator Overloading in Python (with Examples)

Operator overloading in Python

In this tutorial we will learn about Operator Overloading in Python . Before reading this tutorial we recommended to read about below tutorials –

Operator Overloading in Python

Operator Overloading refers to different uses of the same operator in different situations. For example, if we use + operator in between two integer number , it returns their sum, if we use + in between two string, it concatenates them and if we use + in between two lists, it adds the two lists. This various use of the same + operator is called Operator Overloading.

Now the question that may arise in our minds is what will happen if we use the + operator between two objects, we will see it with the help of an example –

Example 1: Try to add two objects using + operator in Python

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary
        
# creating two objects
emp1 = Employee("emp1", 24000)
emp2 = Employee("emp2", 30000)
# using + operator in between
# two objects
print(emp1 + emp2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_10376/3668677629.py in <module>
     10 # using + operator in between
     11 # two objects
---> 12 print(emp1 + emp2)

TypeError: unsupported operand type(s) for +: 'Employee' and 'Employee'

In the above code, a class named Employee has been defined which have two object variables named name and salary. Then two objects of that class named emp1 and emp2 have been created. Then an attempt was made to add two objects using the + operator which raised TypeError.

So we can’t add two objects with the + operator. But Python gives us some methods by which we can add two objects through the + operator, these methods are called Special method or Magic method or Dunder method.

Special method in Python

Inside any Python class those methods which start with double underscore (__) and end with double underscore (__) are called Special method. These methods are different from other methods in the class. Earlier we discussed one such method that is Constructor or __init__() method. Now we will discuss about various types of Special Method in Python –

__str__() and __repr__() method in Python

When we try to print an object of a class, it prints an object which does not make sense at all. With the __str__() and __repr__() method we can control what will print in the output if we print any object. Some of the features of __str__() and __repr__() method are as under –

  • If __str__() or __repr__() method is defined in a class then if we try to print any object of the class then __str__() or __repr__() method is automatically called.
  • If both __str__() and __repr__() methods are defined in a class then the __str__() method is automatically called if we try to print any object in the class. We can also explicitly call __str__() and __repr__() when printing objects.

Example 1: Print an object in Python

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary        
        
# creating object
emp1 = Employee("emp1", 24000)
print(emp1)
<__main__.Employee object at 0x0000023345C6DD90>

In the above code, an object emp1 of Employee class has been printed. Since there is no __str__() or __repr__() method defined in the class, so seeing the output we can not understand anything about the object .

Example 2: Print an object with __repr__() method in Python

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary 
    # defining __repr__ method
    def __repr__ (self):
        return f"{self.name} your salary is {self.salary}"
        
# creating object
emp1 = Employee("emp1", 24000)
print(emp1)
emp1 your salary is 24000

In the above code, when an object emp1 of Employee class is printed, it automatically calls __repr__() method.

Example 3: Print an object with __str__() method in Python

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary 
    # defining __str__ method
    def __str__ (self):
        return f"{self.name} , {self.salary}"
        
# creating object
emp1 = Employee("emp1", 24000)
print(emp1)
emp1 , 24000

In the above code, when an object emp1 of Employee class is printed, it automatically calls __str__() method.

Example 4: Print an object with both __str__() and __repr__() method

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary 
    # defining __repr__ method
    def __repr__ (self):
        return f"{self.name} your salary is {self.salary}"
    # defining __str__ method
    def __str__ (self):
        return f"{self.name} , {self.salary}"
        
# creating object
emp1 = Employee("emp1", 24000)
print(emp1)
print(repr(emp1))
print(str(emp1))
emp1 , 24000
emp1 your salary is 24000
emp1 , 24000

In the above code, when an object emp1 of Employee class is printed, it automatically calls the __str__() method as both __str__() and __repr__() method is defined in the class . But when we have printed the object explicitly calling with __str__() and __repr__() method it has called __str__() and __repr__() method respectively .

Overloading Arithmetic Operators in Python

When we use any arithmetic operator with any object then which special method will be called is shown in a table below –

Expression During Execution
obj1 + obj2obj1.__add__(obj2)
obj1 – obj2obj1.__sub__(obj2)
obj1 * obj2 obj1.__mul__(obj2)
obj1 / obj2 obj1.__truediv__(obj2)
obj1 // obj2 obj1.__floordiv__(obj2)
obj1 % obj2 obj1.__mod__(obj2)
obj1 ** obj2 obj1.__pow__(obj2)
obj1 & obj2 obj1.__and__(obj2)
obj1 ^ obj2 obj1.__xor__(obj2)
obj1 | obj2 obj1.__or__(obj2)

Example 1: Arithmetic Operators Overloading in Python

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary
        
    # for + operator    
    def __add__ (self, other):
        return self.salary + other.salary
    
    # for - operator
    def __sub__ (self, other):
        return self.salary - other.salary
    
    # for * operator
    def __mul__ (self, other):
        return self.salary * other.salary
    
    # for / operator
    def __truediv__ (self, other):
        return self.salary / other.salary
    
    # for // operator
    def __floordiv__ (self, other):
        return self.salary // other.salary
    
    # for % operator
    def __mod__ (self, other):
        return self.salary % other.salary
    
    # for ** operator
    def __pow__ (self, other):
        return self.salary ** other.salary
    
    # for & operator
    def __and__ (self, other):
        return self.salary & other.salary
    
    # for ^ operator
    def __xor__ (self, other):
        return self.salary ^ other.salary
    
    # for | operator
    def __or__ (self, other):
        return self.salary | other.salary
# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

+ Arithmetic Operator Overloading in Python

# using + operator in between two objects
print(emp1 + emp2)
7

– Arithmetic Operator Overloading in Python

# using - operator
print(emp1 - emp2)
3

* Arithmetic Operator Overloading in Python

# using * operator
print(emp1 * emp2)
10

/ Arithmetic Operator Overloading in Python

# using / operator
print(emp1 / emp2)
2.5

// Arithmetic Operator Overloading in Python

# using // operator
print(emp1 // emp2)
2

% Arithmetic Operator Overloading in Python

# using % operator
print(emp1 % emp2)
1

** Arithmetic Operator Overloading in Python

# using ** operator
print(emp1 ** emp2)
25

& Arithmetic Operator Overloading in Python

# using & operator
print(emp1 & emp2)
0

^ Arithmetic Operator Overloading in Python

# using ^ operator
print(emp1 ^ emp2)
7

| Arithmetic Operator Overloading in Python

# using | operator
print(emp1 | emp2)
7

Example 2: Add multiple objects in Python using + operator

If we need to add more than two objects with __add__() method then we can’t do it in the manner mentioned above, we will see adding more than two objects with __add__() method below. For this reason we will use __str__() and __repr__() method .

#defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary

    def __repr__ (self):
        return f"{self.salary}"
    def __add__ (self, other):         
         return Employee(self.name,self.salary + other.salary)
#creating four object
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 3)
emp3 = Employee("emp3", 4)
emp4 = Employee("emp4", 16)
emp = emp1 + emp2 + emp3 + emp4
print(repr(emp))
print(emp.salary)
28
28

When emp1 + emp2 + emp3 + emp4 is written in the above code, first a new object Employee(“emp1”, 8) is created using emp1 + emp2 and __add__() method . Then this new object is added to emp3 and Created another new object Employee (“emp1”, 12), with which emp4 is added to create another new object Employee (“emp1”, 28) which is assigned to emp. So when we print the emp the __repr__() method is automatically called and printed 28 .

In this way other special methods can be used for more than two objects.

Overloading Comparison Operators in Python

In Python we can overload comparison operator like arithmetic operator. When we use any comparison operator with any object then which special method will be called is shown in a table below

Expression
During Execution
obj1 < obj2obj1.__lt__(obj2)
obj1 <= obj2 obj1.__le__(obj2)
obj1 == obj2 obj1.__eq__(obj2)
obj1 != obj2 obj1.__ne__(obj2)
obj1 > obj2 obj1.__gt__(obj2)
obj1 >= obj2 obj1.__ge__(obj2)

Example 1: Comparison Operators Overloading in Python

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary
    # for < operator
    def __lt__ (self, other):
        return self.salary < other.salary    
    # for <= operator
    def __le__ (self, other):
        return self.salary <= other.salary
    # for == operator
    def __eq__ (self, other):
        return self.salary == other.salary
    # for != operator
    def __ne__ (self, other):
        return self.salary != other.salary
    # for > operator
    def __gt__ (self, other):
        return self.salary > other.salary
    # for >= operator
    def __ge__ (self, other):
        return self.salary >= other.salary
# creating two objects
emp1 = Employee("emp1", 30000)
emp2 = Employee("emp2", 35000)

< Comparison Operator Overloading in Python

# using < operator
print(emp1 < emp2)
True

<= Comparison Operator Overloading in Python

# using <= operator
print(emp1 <= emp2)
True

== Comparison Operator Overloading in Python

# using == operator
print(emp1 == emp2)
False

!= Comparison Operator Overloading in Python

# using != operator
print(emp1 != emp2)
True

> Comparison Operator Overloading in Python

# using > operator
print(emp1 > emp2)
False

>= Comparison Operator Overloading in Python

# using >= operator
print(emp1 >= emp2)
False

Overloading Assignment Operators in Python

In Python we can overload assignment operators like arithmetic operators. When we use any assignment operator with any object then which special method will be called is shown in a table below

Expression During Execution
obj1 += obj2obj1.__iadd__(obj2)
obj1 -= obj2obj1.__isub__(obj2)
obj1 *= obj2 obj1.__imul__(obj2)
obj1 /= obj2 obj1.__itruediv__(obj2)
obj1 //= obj2 obj1.__ifloordiv__(obj2)
obj1 %= obj2 obj1.__imod__(obj2)
obj1 **= obj2 obj1.__ipow__(obj2)
obj1 &= obj2 obj1.__iand__(obj2)
obj1 ^= obj2 obj1.__ixor__(obj2)
obj1 |= obj2 obj1.__ior__(obj2)

Example 1: Assignment Operators Overloading in Python

# defining a class
class Employee:
    def __init__ (self, name, salary):
        self.name = name
        self.salary = salary
        
    # for += operator    
    def __iadd__ (self, other):
        self.salary += other.salary
        return self.salary
    
    # for -= operator
    def __isub__ (self, other):
        self.salary -= other.salary
        return self.salary
    
    # for *= operator
    def __imul__ (self, other):
        (self.salary) *= (other.salary)
        return self.salary
    
    # for /= operator
    def __itruediv__ (self, other):
        self.salary /= other.salary
        return self.salary
    
    # for //= operator
    def __ifloordiv__ (self, other):
        self.salary //= other.salary
        return self.salary
    
    # for %= operator
    def __imod__ (self, other):
        self.salary %= other.salary
        return self.salary
    
    # for **= operator
    def __ipow__ (self, other):
        self.salary **= other.salary
        return self.salary
    
    # for &= operator
    def __iand__ (self, other):
        self.salary &= other.salary
        return self.salary
    
    # for ^= operator
    def __ixor__ (self, other):
        self.salary ^= other.salary
        return self.salary
    
    # for |= operator
    def __ior__ (self, other):
        self.salary |= other.salary
        return self.salary

+= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using += operator in between two objects
emp1 += emp2
print(emp1)
7

-= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using -= operator in between two objects
emp1 -= emp2
print(emp1)
3

*= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using *= operator in between two objects
emp1 *= emp2
print(emp1)
10

/= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using /= operator in between two objects
emp1 /= emp2
print(emp1)
2.5

//= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using //= operator in between two objects
emp1 //= emp2
print(emp1)
2

%= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using %= operator in between two objects
emp1 %= emp2
print(emp1)
1

**= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using **= operator in between two objects
emp1 **= emp2
print(emp1)
25

&= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using &= operator in between two objects
emp1 &= emp2
print(emp1)
0

^= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using ^= operator in between two objects
emp1 ^= emp2
print(emp1)
7

|= Assignment Operator Overloading in Python

# creating two objects
emp1 = Employee("emp1", 5)
emp2 = Employee("emp2", 2)

# using |= operator in between two objects
emp1 |= emp2
print(emp1)
7

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply