__eq__ and __lt__
- Python course
- Intermediate
- Lesson 30/116
- 5 min
Learn comparison with __eq__ and __lt__.
__eq__ and __lt__
Magic methods adapt Python's built-in operators to a class. __eq__(self, other) defines the == operator; __lt__(self, other) defines the < operator.
Example: class Point:\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y. Writing p1 == p2 calls __eq__. These methods let you compare and sort instances; sorting uses __lt__.
Sorting with __lt__
__lt__(self, other) defines the < operator. Python's sorted() and list.sort() use it. This method returns True/False.
Example: def __lt__(self, other):\n return self.x < other.x. Now sorted([p1, p2, p3]) orders the points by x. If __lt__ is not defined, sorting raises TypeError. Sortable classes need __lt__.
Practice Add __eq__ to the Point class
Define the Point class. Add def __init__(self, x, y): with self.x = x and self.y = y in the body. Add def __eq__(self, other):; in the body write return self.x == other.x and self.y == other.y. Then call p1 = Point(1, 2), p2 = Point(1, 2) and print(p1 == p2).
Starter code
# Define the Point classSample solution
# Define the Point class
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method does p1 == p2 call?
- __eq__ Correct answer
- __lt__
- __cmp__
- __str__
Explanation: The == operator calls the __eq__ method.
2 Complete the __eq__ body
class Point:
def __eq__(self, other):
return self.x == ____ and self.y == other.y
class Point:
def __eq__(self, other):
return self.x == other.x and self.y == other.y
Explanation: The comparison uses other.x.
3 Match the comparison methods
| Term | Meaning |
|---|---|
__eq__ |
== operator |
__lt__ |
< operator |
sorted(...) |
Uses __lt__ |