Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to overload Python comparison operators?
Python provides magic methods to define custom behavior for comparison operators. The comparison operators (<, <=, >, >=, == and !=) can be overloaded by implementing __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods respectively.
Magic Methods for Comparison Operators
| Operator | Magic Method | Description |
|---|---|---|
== |
__eq__() |
Equal to |
!= |
__ne__() |
Not equal to |
< |
__lt__() |
Less than |
<= |
__le__() |
Less than or equal to |
> |
__gt__() |
Greater than |
>= |
__ge__() |
Greater than or equal to |
Example: Overloading Comparison Operators
The following example demonstrates overloading the == and >= operators for a custom Distance class ?
class Distance:
def __init__(self, x=5, y=5):
self.ft = x
self.inch = y
def __eq__(self, other):
if self.ft == other.ft and self.inch == other.inch:
return True
else:
return False
def __ge__(self, other):
# Convert both distances to inches for comparison
in1 = self.ft * 12 + self.inch
in2 = other.ft * 12 + other.inch
if in1 >= in2:
return True
else:
return False
def __str__(self):
return f"{self.ft} ft {self.inch} inch"
# Create distance objects
d1 = Distance(5, 5)
d2 = Distance()
print(f"d1 ({d1}) == d2 ({d2}): {d1 == d2}")
d3 = Distance(6, 10)
d4 = Distance(5, 5)
print(f"d3 ({d3}) == d4 ({d4}): {d3 == d4}")
d5 = Distance(3, 11)
d6 = Distance()
print(f"d5 ({d5}) >= d6 ({d6}): {d5 >= d6}")
d1 (5 ft 5 inch) == d2 (5 ft 5 inch): True d3 (6 ft 10 inch) == d4 (5 ft 5 inch): False d5 (3 ft 11 inch) >= d6 (5 ft 5 inch): False
Overloading Multiple Comparison Operators
Here's a more complete example that implements multiple comparison operators ?
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __eq__(self, other):
return self.marks == other.marks
def __lt__(self, other):
return self.marks < other.marks
def __le__(self, other):
return self.marks <= other.marks
def __gt__(self, other):
return self.marks > other.marks
def __ge__(self, other):
return self.marks >= other.marks
def __ne__(self, other):
return self.marks != other.marks
def __str__(self):
return f"{self.name}: {self.marks}"
# Create student objects
alice = Student("Alice", 85)
bob = Student("Bob", 92)
charlie = Student("Charlie", 85)
print(f"{alice} == {charlie}: {alice == charlie}")
print(f"{alice} < {bob}: {alice < bob}")
print(f"{bob} > {alice}: {bob > alice}")
print(f"{alice} != {bob}: {alice != bob}")
Alice: 85 == Charlie: 85: True Alice: 85 < Bob: 92: True Bob: 92 > Alice: 85: True Alice: 85 != Bob: 92: True
Key Points
- Magic methods should return
TrueorFalsefor proper boolean comparison - You don't need to implement all comparison operators ? Python can derive some from others
- The
__ne__()method is automatically derived from__eq__()in Python 3 - Always ensure your comparison logic is consistent and follows mathematical rules
Conclusion
Overloading comparison operators allows you to define custom comparison logic for your classes. Implement the appropriate magic methods like __eq__(), __lt__(), etc., to enable natural comparison syntax between objects of your custom classes.
Advertisements
