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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago