Python Tutorial Python Advanced Python References Python Libraries

Python - Comparison Operator Overloading



Comparison operators are those operators which compares two operand, like operators (==, <, >, <=, >=) compares Python data types. Following is the list of comparison operators and corresponding magic methods that can be overloaded in Python.

OperatorMagic Method
<__lt__(self, other)
>__gt__(self, other)
<=__le__(self, other)
>=__ge__(self, other)
==__eq__(self, other)
!=__ne__(self, other)

Python allows us to specify these operators with a special meaning for a class object.

Example: overloading comparison operators

In the example below, comparison operators < and > are overloaded. When it is applied with point objects, it compares its distance from origin and returns true or false based on the comparison result. For example:

  • (10, 15) > (5, 25) will compare 10² + 15² > 5² + 25² which is equivalent to 325 > 650, hence returns false.
  • (10, 15) < (12, 14) will compare 10² + 15² < 12² + 14² which is equivalent to 325 < 340, hence returns true.

Note: In this example, math module's hypot function is used to calculate distance of a point from the origin.

import math class point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "({0},{1})".format(self.x, self.y) #function for operator overloading < def __lt__(self, other): d1 = math.hypot(self.x, self.y) d2 = math.hypot(other.x, other.y) res = True if d1 < d2 else False return res #function for operator overloading > def __gt__(self, other): d1 = math.hypot(self.x, self.y) d2 = math.hypot(other.x, other.y) res = True if d1 > d2 else False return res #creating point objects p1 = point(10, 15) p2 = point(5, 25) p3 = point(12, 14) #using overloaded < and > operators #with point objects print("(p1 > p2) returns:", (p1>p2)) print("(p1 < p3) returns:", (p1<p3)) 

The output of the above code will be:

 (p1 > p2) returns: False (p1 < p3) returns: True 

❮ Python - Operator Overloading