×

Operator Overloading in Python

Operator Overloading is making an operator perform some action other than an existing option. Python does support Operator Overloading.

The main usage of Operator Overloading in Python is we can also make the operator perform a particular task irrespective of the arguments that we pass to it.

* is overloaded
3 * 2 = 6
"h" * 3 = "hhh"

For this, we need to define the magic method of the operator.

Basically when we use the “+” operator then based on the arguments we pass, the behavior of the operator changes. This is because the “+” operator calls the magic method of the argument we pass.

If the argument class has the magic method for the “+” operator then it performs the assigned task, else it returns an error.

# Addition Operator "+"

3 + 5   -> 8

Here, we are passing 3 and 5 as arguments to the “+” operator. Since 3 and 5 are integers internally the “+” operator checks whether there is a magic method __add__() for 3( <class 'int'> ) and 5( <class 'int'> ). The int class magic method __add__() comes as in-built it performs the addition operation without throwing any error.

# Addition Operator "+"

print(type(3), type(5))

# __dict__ returns members of int class
print(int.__dict__)


# Output
<class 'int'>
mappingproxy(
 {'__abs__': <slot wrapper '__abs__' of 'int' objects>,
 '__add__': <slot wrapper '__add__' of 'int' objects>,
 '__and__': <slot wrapper '__and__' of 'int' objects>,
 ---
 ----
})

In the same way, we can define a __add__() magic method for an object and add two or more objects of a class and return the addition result.

Overloading “+” operator with two objects

In the below example, we are adding two objects salary and bonus to calculate the Total_income. But since the salary and bonus are not integers as they are two objects, python returns an error.

print(salary + bonus) 

We need to define a magic method in the class of the first argument we have passed which is salary. Because, when the “+” operator is used it looks for the magic method( __add__() ) in the class of the first argument( “salary” ).

Since we need to add salary and bonus objects we pass two reference variables self_1 and self_2. self_1 points to the salary object which has an income value of 10000, and self_2 points to the bonus object which has an income value of 5000. And finally, we return the result.

class employee:
    def __init__(self, income):
        self.income = income
    def __add__(self_1, self_2):
        Total_income = self_1.income + self_2.income
        return Total_income

salary = employee(10000)
bonus = employee(5000)
print(salary + bonus) 

# Output
15000

Overloading “*” operator with two objects

In this section, we try to overload the multiplication operator( * ) with two objects. Basically, the * operator can act like a multiplication or string repetition operator. But to multiply two objects we need to define the magic method of the first object that we are passing.

The magic method of the * operator is __mul__(). We need to define __mul__() inside the class of first object that we are passing.

Since we need to multiply fuel and price objects we pass two reference variables self_1 and self_2. The self_1 points to the fuel object which has a fuel_litres of 20, and self_2 points to the price object which has a fuel_price of 5000. And finally, we return the result as the total amount.

class car:
  def __init__(self, fuel_litres):
    self.fuel_litres = fuel_litres
  def __mul__(self_1, self_2):
    Total_Amount = self_1.fuel_litres * self_2.fuel_price
    return Total_Amount
class fuel_price:
  def __init__(self, fuel_price):
    self.fuel_price = fuel_price 


fuel = car(20)
price = fuel_price(100)
print(fuel * price, "/-") 

# Output
2000/-

Note:- fuel * price and price * fuel are not the same. To calculate price * fuel we need to define the __mul__() method in the price class. Because the * operator looks for the magic method in the class of the first argument that we have passed.