Categories: python

Operator Overloading in Python

Operator overloading refers to providing meaning that extends beyond their predefined operational meaning. For example, the operator + can be used to add two integers, join two strings, or merge two lists. It is possible because the ‘+’ operator is overloaded by the int and str classes. Therefore, the different behavior of a single operator for different types of operands is called Operator Overloading.

Example:

print (114 + 32)  
   
# Now, we will concatenate the two strings  
print ("coding" + "is fun")  
   
# We will check the product of two numbers  
print (10 * 14)  
   
# Here, we will try to repeat the String  
print ("X Y Z " * 4)

Output:

146
codingis fun
140
X Y Z X Y Z X Y Z X Y Z 

How to overload the operators in Python?

If we have two objects that are physical representations of a class (user-defined data type) and we try to add them using the binary ‘+’ operator, the compiler throws an error because it doesn’t know how to add two objects. So we define a method for an operator, which is known as operator overloading. We can overload any existing operator, but not create a new one. Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator to perform operator overloading. When we use the + operator, for example, the magic method add is automatically invoked, which defines the operation for the + operator.

How Does Operator Overloading Function?

When you change the behavior of an existing operator by overloading it, you must redefine the special function that is called automatically when the operator is used with objects.

For Example: adding two objects

class Code:  
    def __init__(self, X):  
        self.X = X  
   
    # adding two objects  
    def __add__(self, U):  
        return self.X + U.X  
object_1 = Code( int( input( print ("Please enter the value: "))))  
object_2 = Code( int( input( print ("Please enter the value: "))))  
print (": ", object_1 + object_2)  
object_3 = Code(str( input( print ("Please enter the value: "))))  
object_4 = Code(str( input( print ("Please enter the value: "))))  
print (": ", object_3 + object_4) 

Output:

Please enter the value: 12
Please enter the value: 
45
:  57
Please enter the value: 
19
Please enter the value: 
32
:  1932

For Example: Overloading comparison operator

class Code:  
    def __init__(self, X):  
        self.X = X  
    def __gt__(self, U):  
        if(self.X > U.X):  
            return True  
        else:  
            return False  
object_1 = Code(int( input( print ("Please enter the value: "))))  
object_2 = Code(int (input( print("Please enter the value: "))))

if(object_1 > object_2):  
    print ("The object_1 is greater than object_2")  
else:  
    print ("The object_2 is greater than object_1")  

Output:

Please enter the value: 
112
Please enter the value: 
34
The object_1 is greater than object_2
Special Functions for Operator Overloading:

Python’s special functions are those that are used to perform specific tasks. As with the init() method, which is also a special function, these special functions have __ as a prefix and suffix to their names.

Binary Operators:
OperatorMagic Function
+__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:
OperatorMagic Function
<__LT__(SELF, OTHER)
>__GT__(SELF, OTHER)
<=__LE__(SELF, OTHER)
>=__GE__(SELF, OTHER)
==__EQ__(SELF, OTHER)
!=__NE__(SELF, OTHER)
Assignment Operators:
OperatorMagic Function
-=__ISUB__(SELF, OTHER)
+=__IADD__(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:
OperatorMagic Function
__NEG__(SELF, OTHER)
+__POS__(SELF, OTHER)
~__INVERT__(SELF, OTHER)

Example:


class Code:
 def __init__(self, c):
  self.c = c

 # Overloading ~ operator, but with two operands
 def __invert__(self):
  return "This is the ~ operator, overloaded as binary operator."


ob1 = Code(2)

print(~ob1)

Output:

This is the ~ operator, overloaded as binary operator.

Note: also read about Static Keyword in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 days ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago