In this lesson, you’ll learn how to make your custom objects comparable using standard relational operators like <, >, and == by implementing "rich comparison" dunder methods.
Why use rich comparison?
By default, Python doesn't know how to compare two instances of your custom classes. If you try to use obj1 < obj2, Python will raise a TypeError. To fix this, you define special "dunder" (double underscore) methods that translate these operators into logic your object understands.
The Six Comparison Methods
There are six methods you can implement to define how your objects relate to each other:
__eq__(self, other): Equality (==)__ne__(self, other): Not equal (!=)__lt__(self, other): Less than (<)__gt__(self, other): Greater than (>)__le__(self, other): Less than or equal (<=)__ge__(self, other): Greater than or equal (>=)
A Concrete Example
Imagine a Box class where we want to compare boxes based on their volume:
class Box:
def __init__(self, volume):
self.volume = volume
def __eq__(self, other):
return self.volume == other.volume
def __lt__(self, other):
return self.volume < other.volume
box_a = Box(10)
box_b = Box(20)
print(box_a < box_b) # Output: True
print(box_a == box_b) # Output: False
Pro-Tip: Return NotImplemented
If you compare your object with a type it doesn't support, you should return the special constant NotImplemented. This tells Python to try the reverse operation on the other object (e.g., if box_a < 5 fails, Python will check if 5 > box_a is defined).
While you can define all six methods, Python is smart enough to handle some logic for you. For instance, if you define __eq__ and __lt__, you can use the functools.total_ordering decorator to automatically generate the remaining four comparison methods based on your logic, saving you from writing extra code.
Key Takeaway: By implementing rich comparison dunder methods, you transform your custom objects from passive data holders into active participants in Python’s expression syntax.