typestar

__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

  1. __repr__ returns code-like text for debugging.
  2. !r inside the f-string quotes the fields properly.
  3. __eq__ compares field tuples, so equal cards match.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 5 in Classes, step 42 of 72 in Language basics.

← Previous Next →