__repr__ and __eq__ in Python
Teaching objects to print themselves and compare by value.
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __repr__(self):
return f"Card({self.rank!r}, {self.suit!r})"
def __eq__(self, other):
return (self.rank, self.suit) == (other.rank, other.suit)
ace = Card("A", "spades")
same = Card("A", "spades")
matches = ace == same
How it works
__repr__returns code-like text for debugging.!rinside the f-string quotes the fields properly.__eq__compares field tuples, so equal cards match.
Keywords and builtins used here
Cardclassdefreturnself
The run, in numbers
- Lines
- 15
- Characters to type
- 304
- Tokens
- 103
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 62 seconds.
Step 4 of 5 in Classes, step 42 of 72 in Language basics.