How to overload an operator in Python

Operator overloading is used to customize the function of an operator (e.g., +,*,<,== etc.) for a user-defined class. It is necessary to overload the operator we want to use with the user-defined data type, without it, the compiler does not know which variables of the user-defined type to add, multiply, or compare.

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading ==.

Chaining

In the context of operator overloading, chaining is when you use an operator multiple times in the same line:

# Passing salary as argument to constructor:
a = Person(5000)
b = Person(10000)
c = Person(15000) 

# Using '+' two times:
a + b + c

To make an overloaded operator capable of performing chaining, we usually return the same user-defined type in the overloading function:

def __add__(self, x):
    return Person(self.salary + x.salary)
How chaining works
How chaining works

Example

class Fruit:
def __init__(self, weight, name = "none"):
self.name = name;
self.weight = weight;
def __add__(self, x):
if isinstance (x, Fruit):
return Fruit(self.weight + x.weight)
if isinstance (x, int):
return Fruit(self.weight + x, self.name)
def __eq__(self, x):
# Comparing names and not weights:
if self.name == x.name:
print("Both are the same fruits")
else:
print(self.name, "and", x.name, "are different fruits.")
# Overloading __str__() to use print(Fruit):
def __str__(self):
if self.name == "none":
return "Weight: {0}\n".format(self.weight)
else:
return "Name: {0}, Weight: {1}\n".format(self.name, self.weight)
a = Fruit(5, "Strawberry")
b = Fruit(100, "Watermelon")
c = Fruit(20, "Mango")
print(a, b, c)
print(a + b + c)
a == b

Operator-method lists

Basic arithmetic operators

Operator Method
+ __add__()
- __sub__()
* __mul__()
/ __truediv__()

Comparison Operators

Operator Method
< __lt__()
<= __le__()
== __eq__()
!= __ne__()
>= __ge__()
> __gt__()

Refer to the Official Python Docs to get a list of all the operators in Python.

Copyright ©2024 Educative, Inc. All rights reserved