Introduction
You've probably noticed that the same built-in operator or function behaves differently for objects of different classes; this is known as Operator Overloading.
Operator overloading is a Python feature that allows the same operator to have different meanings depending on the context.
Let's understand with an example,
# A function to show the use of the + operator for multiple purposes.
# '+' is used to add two integers.
print(2 + 2)
# '+' is used to concatenate two strings.
print("Coding "+"Ninjas")
Output
4
Coding Ninjas
Here, the operator + adds two integers, joins two strings, or merges two lists. It is only possible because the '+' operator is overloaded by the int and str classes.
Similarly, the ‘*’ operator is used to multiply two numbers or repeat a string.
Read About, Divmod in Python and Convert String to List Python.
How to overload the operators in Python?
In Python, each class defines its behavior for built-in functions and methods. When you pass a class instance to a built-in function or use an operator on the instance, you are actually calling a special method with the relevant arguments.
Consider the following scenario: we have two objects that are physical representations of a class (user-defined data type). When we add two objects with the binary '+' operator, the compiler throws an error since it does not know how to add two objects. As a result, we define a method for an operator, known as operator overloading.
Python provides some special or magic function that is automatically invoked when associated with that operator to perform operator overloading.
For example, when we use the + operator, the magic method __add__ is automatically invoked, which defines the action for the + operator.
Note: We can overload all existing operators, but we can't create new ones.
Let's understand the overloading of multiple operators one by one.
Must Read, python ord
Also Read About, Python for Data Science
Overloading binary + operator in Python
When we use an operator on user-defined data types, a special or magic function associated with that operator is immediately invoked. Changing the behavior of an operator is as straightforward as changing the behavior of a method or function. Methods are declared in your class, and operators operate by the behavior defined in the methods.
When we use the ‘+’ operator, the magic function __add__ is immediately performed, which defines the action for the + operator. We may add more significance to the + operator by modifying the code of this magic method.
Let's understand this by modifying the __add__ to add two objects of a user-defined class.
# Function to show how to overload the + operator to add two objects.
class Example:
def __init__(self, x):
self.x = x
# defining the __add__ function to add two objects.
def __add__(self, o):
return self.x + o.x
obj1 = Example(2)
obj2 = Example(2)
obj3 = Example("Coding ")
obj4 = Example("Ninjas")
# adding two objects.
print(obj1 + obj2)
print(obj3 + obj4)
Output
4
Coding Ninjas
Here, when you use obj1 + obj2, Python calls obj1.__add__(obj2), which in turn is Example.__add__(obj1, obj2). After that, the addition operation is carried out in the manner that we described.
Overloading Comparison Operators
Python does not restrict operator overloading to simply arithmetic operators. We can also overload comparison operators.
Let’s overload greater than( > ) operator for two objects.
When using the ‘>’ operator, the magic function is __gt__.
# Function to overload greater than operator.
class Example:
def __init__(self, x):
self.x = x
def __gt__(self, o):
if(self.x > o.x):
return True
else:
return False
obj1 = Example(4)
obj2 = Example(2)
if(obj1 > obj2):
print("obj1 is greater than obj2")
else:
print("obj2 is greater than obj1")
Output
obj1 is greater than obj2
Must Read Python List Operations
Let’s now overload less than( < ) operator for two objects.
When using the ‘<’ operator, the magic function is __lt__.
# Function to overload smaller than operator.
class Example:
def __init__(self, x):
self.x = x
def __lt__(self, o):
if(self.x < o.x):
return True
else:
return False
obj1 = Example(4)
obj2 = Example(2)
if(obj1 < obj2):
print("obj1 is less than obj2")
else:
print("obj2 is less than obj1")
Output
obj2 is less than obj1
Overloading Equality ( = ) operator for two objects.
When using the ‘=’ operator, the magic function is __eq__.
# Function to overload greater than operator
class Example:
def __init__(self, x):
self.x = x
def __lt__(self, o):
if(self.x == o.x):
return True
else:
return False
obj1 = Example(4)
obj2 = Example(2)
if(obj1 == obj2):
print("obj1 is equal to obj2")
else:
print("obj2 is not equal to obj1")
Output
obj2 is not equal to obj1
Similarly, we can overload multiple other operators as well. The magic function for the operators is tabulated below.
You can compile it with online python compiler.
Operator |
Magic Function |
+ |
__add__(self, o) |
- |
__sub__(self, o) |
* |
__mul__(self, o) |
/ |
__truediv__(self, o) |
// |
__floordi__(self, o) |
% |
__mod__(self, o) |
** |
__pow__(self, o) |
>> |
__rshift__(self, o) |
<< |
__lshift__(self, o) |
& |
__and__(self, o) |
| |
__or__(self, o) |
^ |
__xor__(self, o) |
<= |
__le__(self, o) |
>= |
__ge__(self, o) |
== |
__eq__(self, o) |
!= |
__ne__(self, o) |
Read more, Fibonacci Series in Python