Fix the Broken Equality Check
Intermediate · Fix the bug · from Python Magic Methods: The Complete __dunder__ Guide
From the lesson: Python Magic Methods: The Complete __dunder__ Guide
Think of a TV remote control. You press the volume button, and the TV gets louder. You press the channel button, and it switches channels. You don't think about how it works - you just press the button and the TV responds.
Read the lessonThis Coordinate class has a broken __eq__ method. Two coordinates with the same x and y should be equal, but they aren't. Find and fix the bug.
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.x # Bug!
def __repr__(self):
return f'Coordinate({self.x}, {self.y})'
a = Coordinate(3, 4)
b = Coordinate(3, 4)
c = Coordinate(3, 5)
print(a == b)
print(a == c)
More Magic Methods exercises
- Add String Representations to a BookBeginner
- Build a Team with __len__Beginner
- Make a Gradebook IndexableIntermediate
- Predict the Magic Method OutputIntermediate
- Make Tasks Sortable by PriorityIntermediate
- Create a Callable FormatterAdvanced
- Refactor a Playlist with Magic MethodsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz