Lessons · Python · __repr__ and __eq__
What an object shows, and when two are equal
__repr__ decides how an object looks when printed or inspected. __eq__ decides what == means; without it, == asks whether two names point at the same object.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
You will print an object to see what went wrong and get <Point object at 0x7f...>, which tells you nothing. And a test that compares two results with == will fail on identical values until you say what equal means.
How to think about it
Give every class you debug a __repr__ that reads like the call that would rebuild it. Give a class __eq__ only when two objects with the same values should count as the same thing.
Worked example
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):How it shows in the shell, lists and errors.
return f'Point({self.x}, {self.y})'Reads like code that rebuilds it.def __eq__(self, other):What == means.
return (self.x, self.y) == (other.x, other.y)Same values, same point.
print(Point(1, 2), Point(1, 2) == Point(1, 2))Point(1, 2) True
Your turn
Make the object print as Money(5).
class Money:
def __init__(self, amount):
self.amount = amount
def (self):
return f'Money({self.amount})'Solve one with the tests running
The trap
Expecting == to compare values by default. Point(1, 2) == Point(1, 2) is False until you define __eq__; the two are different objects that happen to match.