Python operator overloading allows a single operator to perform more than one operation based on the class (type) of operands. For example operator + is used to add two integers as well as join two strings and merge two lists.
The ‘+’ operator is overloaded by int class and str class and this is called Operator Overloading.
Python operator overloading
Simple example code the
+ operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.
# addition on two numbers print(10 + 20) # concatenate two strings print("Hello" + "World") # merge two lists list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3)
For example user has two objects which are the physical representation of a user-defined data type class. The user has to add two objects using the “+” operator, and
TypeError raised, since Python didn’t know how to add two
Point objects together.
However, we can achieve this task in Python through operator overloading.
Python Special Functions: Class functions that begin with a double underscore
__ are called special functions in Python.
Using special functions, we can make our class compatible with built-in functions.
>>> p1 = Point(2,3) >>> print(p1) <__main__.Point object at 0x00000000031F8CC0>
Overloading binary + operator in Python
class A: def __init__(self, a): self.a = a # adding two objects def __add__(self, o): return self.a + o.a ob1 = A(10) ob2 = A(20) ob3 = A("A") ob4 = A("B") print(ob1 + ob2) print(ob3 + ob4)
Overloading comparison operators in Python
class A: def __init__(self, a): self.a = a def __gt__(self, other): if(self.a>other.a): return True else: return False ob1 = A(2) ob2 = A(3) if(ob1>ob2): print("ob1 is greater than ob2") else: print("ob2 is greater than ob1")
Output: ob2 is greater than ob1
Python magic functions used for operator overloading:
Do comment if you have any doubts or suggestions on this Python operator topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.