Python Operator overloading

Operator overloading is making operator(such as +, – , *, // etc.) to perform more then one operation. For instance, the same + (plus) operator perform arithmetic operation with numbers, concatenation of two string and merging of elements in two list. Operator overloading simply means giving it different behavior in different context. Let’s see by adding two points. To overload + operator you need to override __add__() special method. 

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "({0},{1})".format(self.x, self.y)

    # Overloading + operator in python
    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Point(x, y)

p1 = Point(2, 3)
p2 = Point(-1, 2)
print(p1 + p2)



Similarly we can overloading other operator such as -, * , //, %, < , > , etc. Following is  a list of methods to use while overloading these operators.

OperationUsageOverriding method
Additionp1 + p2p1.__add__(p2)
Subtractionp1 – p2p1.__sub__(p2)
Multiplicationp1 * p2p1.__mul__(p2)
Divisionp1 / p2p1.__truediv__(p2)
Floor Divisionp1 // p2p1.__floordiv__(p2)
Powerp1 ** p2p1.__pow__(p2)
Remainderp1 % p2p1.__mod__(p2)
Bitwise left shiftp1 << p2p1.__lshift__(p2)
Bitwise right shiftp1 >> p2p1.__rshift__(p2)
Bitwise ORp1 | p2p1.__or__(p2)
Bitwise ANDp1 & p2p1.__and__(p2)
Bitwise NOT~ p1 p1.__invert__()
Bitwise XORp1 ^ p2p1.__xor__(p2)
Less thanp1 < p2p1.__lt__(p2)
Less than or equal top1 <= p2p1.__le__(p2)
equal to p1 == p2p1.__eq__(p2)
Not equal top1 != p2p1.__ne__(p2)
Greater thanp1 > p2p1.__gt__(p2)
Greater than or equal top1 >= p2p1.__ge__(p2)

Leave a Reply

Your email address will not be published. Required fields are marked *