Operator Overloading in Python

Introduction

Operators are special symbols that perform mathematical expressions. Providing the extended meaning to operators is called operator overloading. The same built-in operators or functions shows different behaviour under different scenarios.

How operator overloading can be achieved?

In Python programming, there are a set of special functions which get automatically invoked when associated with that operator. These special functions contain the implementation of operations to be performed by the operator. For example, when we use the addition operator, the function _add_ is automatically invoked. The function _add_ contains the implementation of + operator. Therefore, by modifying the code of special functions, one can extend the functionality of the operator.

Special functions for Operator Overloading

Binary operator

OperatorsPython methods
+_add_(self, other)
_sub_(self, other)
*_mul_(self, other)
/_truediv_(self, other)
//_floordiv_(self, other)
%_mod_(self, other)
**_pow_(self, other)
>> _rshift_(self, other)
<< _lshift_(self, other)
&_and_(self, other)
|_or_(self, other)
^_xor_(self, other)

Comparison Operators

OperatorsPython methods
_LT_(self, other)
_GT_(self, other)
<=_LE_(self, other)
>=_GE_(self, other)
==_EQ_(self, other)
!=_NE_(self, other)

Assignment Operators

OperatorsPython methods
+=_IADD_(self, other)
-=_ISUB_(self, other)
*=_IMUL_(self, other)
/=_IDIV_(self, other)
//=_IFLOORDIV_(self, other)
%=_IMOD_(self, other)
**=_IPOW_(self, other)
>>=_IRSHIFT_(self, other)
<<=_ILSHIFT_(self, other)
&=_IAND_(self, other)
|=_IOR_(self, other)
^=_IXOR_(self, other)

Unary Operator

OperatorsPython methods
+_NEG_(self, other)
_POS_(self, other)
~_INVERT_(self, other)

Program

Example 1:

class demo:
    def __init__(self, x, y):
        self.x = x
    def __add__(self, other):
        return self.x + other.x + self.y +other.y

num1 = 1
num2 = 5
print(num1+num2)

Output

6

Example 2:

class demo:
    def __init__(self, x, y):
        self.x = x
    def __add__(self, other): 
        return self.x + other.x 

str1 = "Operator"
str2 = "Overloading"
print(str1+str2)

Output:

OperatorOverloading

Example 3:

class OperatorOverloading:
    def __init__(self, obj):
        self.obj = obj
    def __lt__(self, other):
        if(self.obj > other.obj):
            return "A is less than B"
        else:
            return "B is less than A"
    def __eq__(self, other):
        if(self.obj == other.obj):
            return "A == B"
        else:
            return "A != B"
                  
A = OperatorOverloading(3)
B = OperatorOverloading(3)
print(A == B)
  
A = OperatorOverloading(5)
B = OperatorOverloading(6)
print(A > B)

Output:

A == B

A is less than B

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.