Google News
logo
Python Operator Overloading
Python operators work for built-in classes. But same operator behaves differently with different types. 

This feature in Python, that allows same operator to have different meaning according to the context is called operator overloading.

You have already seen you can use + (addition arithmetic  operator for adding numbers and at the same time to concatenate strings. It is possible because +  operator is overloaded by both int  class and str  class. The operators are actually methods defined in respective classes. Defining methods for operators is known as operator overloading. For e.g. To use +  operator with custom objects  you need to define a method called __add__  .
>>> class GridPoint:
    def __init__(self, x, y):  
        self.x = x  
        self.y = y
    def __add__(self, other):
        return GridPoint(self.x + other.x, self.y + other.y)
    def __str__(self):
        string = str(self.x)  
        string = string + ", " + str(self.y)  
        return string

>>> point1 = GridPoint(18, 25)
>>> point2 = GridPoint(-7, 13)
>>> point3 = point1 + point2
>>> print(point3)
11, 38
>>> 
Operator Description Method
+Addition__add__(self, other)
Subtraction__sub__(self, other)
*Multiplication__mul__(self, other)
/True Division__truediv__(self, other)
//Floor Division__floordiv__(self, other)
%Remainder__mod__(self, other)
**Power__pow__(self, other)
&Bitwise AND__and__(self, other)
|Bitwise OR__or__(self, other)
^Bitwise XOR__xor__(self, other)
~Bitwise NOT__not__(self, other)

Relational Operators in python

Relational operators are overloaded in a very similar way in python. But the difference is, those operators often return true/false instead of another instance of the object. Let’s work with an example..

>>> class My_Sample:
	def __init__(self, x, y):
		self.x = x
		self.y = y
	def __gt__(self, other):
		return self.x > other.x
	def __str__(self):
		string = str(self.x)
		string = string + ", " + str(self.y)
		return string

	
>>> point1 = My_Sample(18, 25)
>>> point2 = My_Sample(-7, 13)
>>> if point1 > point2:
	print('point1 is greater than point2')
else:
	print('point1 is not greater than point2')

	
point1 is greater than point2
>>> 

The conventional ‘>’ operator returns true if the operand in the left side of it is greater than the right one. We are going to use this property to compare two instances of class My_Sample.

OperatorDescriptionMethod
>Greater than__gt__(self, other)
>=Greater than or equal to__ge__(self, other)
<Less than__lt__(self, other)
<=Less than or equal to__le__(self, other)
==Equal to__eq__(self, other)
!=Not equal to__ne__(self, other)