__eq__ and __lt__: comparing objects
🌍 In real life. You and a friend each have a 500-taka note. They are two different pieces of paper, but at a shop they are worth the same: either one buys the same things.
Python can't guess what "the same" means for your class. Without help, a == b only asks "is this the very same object?", like asking whether two notes are one piece of paper. Watch: two Money objects with the same amount, and still a == b is False.
The idea in one sentence: __eq__ teaches == what "equal" means for your class, and __lt__ teaches <, which also makes sorted, min and max work.
Its words:
__eq__(self, other): return True when the two count as equal__lt__(self, other): return True whenselfis smaller- identity: without
__eq__,==only checks whether they're the very same object
Teach your class what equal means with __eq__(self, other). Return True when the two should count as equal. Python turns a == b into a.__eq__(b), and a != b uses it too.
To say which one is smaller, write __lt__(self, other) ("less than"). Then < works, and so do sorted(), min() and max(), because they all compare with <.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __lt__(self, other):
return self.marks < other.marks
def __repr__(self):
return f"{self.name}({self.marks})"
students = [Student("Ana", 82), Student("Bo", 67), Student("Cy", 91)]
print(sorted(students))
print(min(students), max(students))Step by step, for any comparison method:
- it takes
self(the left side) andother(the right side) - compare the attributes that matter, like
self.marks < other.marks - return True or False; forgetting
returngives None, which counts as False
The other four for free: @total_ordering. With only __eq__ and __lt__, < works but a > b and a <= b still need methods of their own. Put @total_ordering (from functools) above the class, and Python writes <=, > and >= from the two you gave.
from functools import total_ordering
@total_ordering
class Money:
def __init__(self, amount):
self.amount = amount
def __eq__(self, other):
return self.amount == other.amount
def __lt__(self, other):
return self.amount < other.amount
a, b = Money(500), Money(100)
print(a > b, a >= b, b <= a, a != b)Why must I write them? Python can't guess which attributes matter: two Money objects might be equal by amount, two students by roll number. You decide, once, in one method, and every ==, < and sorted() uses that rule.
Mistakes and edge cases.
- Comparing without lt.
m1 < m2givesTypeError: '<' not supported between instances of 'M' and 'M'. - Forgetting return. A comparison method that returns nothing gives
None, which counts as False. - eq without hash. Writing
__eq__makes objects unhashable, so they can't go in a set (Lesson 24.5). - Comparing different types.
money == 5calls your__eq__with an int; check the type first, orother.amountraises an AttributeError.
Quiz
What does this print?
class Note: def __init__(self, value): self.value = value a = Note(500) b = Note(500) print(a == b, a == a)What does this print?
class Note: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value print(Note(500) == Note(500), Note(500) != Note(100))What does Python turn
x < yinto?- x.__lt__(y)
- y.__lt__(x)
- x.__eq__(y)
What does this print?
class Box: def __init__(self, size): self.size = size def __lt__(self, other): return self.size < other.size boxes = [Box(5), Box(2), Box(9)] print([b.size for b in sorted(boxes)])Which line has a mistake?
class Card: def __init__(self, rank): self.rank = rank def __eq__(self, other): self.rank == other.rank print(Card(7) == Card(7))A class defines eq and lt and has @total_ordering above it. Which comparisons work?
- All six: ==, !=, <, <=, > and >=
- Only == and <
- Only <, because total_ordering replaces __eq__
Coding tasks
Give
Notean__eq__so two notes are equal when they have the samevalue.Give
Studentan__lt__that comparesmarks, sosorted()puts students from the lowest marks to the highest.Write a class
Parcel(weight)with__eq__(same weight) and__lt__(lighter comes first).