Table of Contents


Case study: Bisca

The examples in this note model Bisca, a popular Portuguese card game. We will build card classes step by step and use them to explore inheritance, factory patterns, composition, and Python’s special (“dunder”) methods.

Reference: https://pt.wikipedia.org/wiki/Bisca

The implicit superclass — object

Every class implicitly inherits from object. Even a bare class definition is itself an object — an instance of type:

port = 22
port.__class__

Output:

int
class X:
    pass
X.__class__

Output:

type
X.__class__.__base__

Output:

object

Class hierarchy

An instance of X would have __class__ → X; the class X itself has __class__ → type (it is a class object) and __base__ → object (its superclass).

Card classes with inheritance

A base Card class holds the common state; each subclass provides its own point rule by overriding the _points() method:

class Card:
    """Generic card class"""
 
    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = rank
        self.points = self._points()
class NumberCard(Card):
    def _points(self):
        if self.rank == '7':
            return 10
        else:
            return 0
 
class FaceCard(Card):
    def _points(self):
        match(self.rank):  # Python 3.10+
            case 'Q':
                return 2
            case 'J':
                return 3
            case 'K':
                return 4
            case _:
                raise ValueError(f'Card "{self.rank}" is not a FaceCard')
 
class AceCard(Card):
    def _points(self):
        return 11
cards = [AceCard('A', '\u2660'), NumberCard('2', '\u2660'), FaceCard('J', '\u2660')]
cards[0].__dict__

Output:

{'suit': '♠', 'rank': 'A', 'points': 11}

Creating constants — Strategy design pattern

Suits are modelled as objects rather than plain strings, so each card carries a rich value (name + symbol). This is a lightweight application of the Strategy pattern.

Reference: https://refactoring.guru/design-patterns/behavioral-patterns

class Suit:
    def __init__(self, name, symbol):
        self.name = name
        self.symbol = symbol
Club, Diamond, Heart, Spade = Suit('Club', '\u2663'), Suit('Diamond', '\u2666'), Suit('Heart', '\u2665'), Suit('Spade', '\u2660')
cards = [AceCard('A', Spade), NumberCard('2', Spade), NumberCard('3', Spade)]

Initializing with a factory function

A factory function centralizes the decision of which class to instantiate based on the rank:

def card_factory(rank, suit):
    """Factory function"""
    if rank == 1:
        return AceCard('A', suit)
    elif 2 <= rank < 11:
        return NumberCard(str(rank), suit)
    elif 11 <= rank < 14:
        name = {11: 'Q', 12: 'J', 13: 'K'}[rank]  # PEP20 Simplicity ???
        return FaceCard(name, suit)
    else:
        raise Exception("Rank out of range")
deck = [card_factory(rank, suit) for rank in range(1, 14) for suit in (Club, Diamond, Heart, Spade)]
for c in deck:
    if c.points:
        print(c.rank, c.suit.symbol, c.points, sep=' | ')

Output:

A | ♣ | 11
A | ♦ | 11
A | ♥ | 11
A | ♠ | 11
7 | ♣ | 10
7 | ♦ | 10
7 | ♥ | 10
7 | ♠ | 10
Q | ♣ | 2
Q | ♦ | 2
Q | ♥ | 2
Q | ♠ | 2
J | ♣ | 3
J | ♦ | 3
J | ♥ | 3
J | ♠ | 3
K | ♣ | 4
K | ♦ | 4
K | ♥ | 4
K | ♠ | 4

Alternative factory implementations

Simplicity using mapping and class objects

Python dictionaries can map ranks directly to class objects, since classes are first-class values. First, a refresher on dict.get with a default:

abcd = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
abcd.get('Z', 'Error')

Output:

'Error'

Two dictionaries — one for the class, one for the rank string:

def card_class(rank, suit):
    class_ = {1: AceCard, 7: NumberCard, 11: FaceCard, 12: FaceCard, 13: FaceCard}.get(rank, NumberCard)
    rank_str = {1: 'A', 11: 'J', 12: 'Q', 13: 'K'}.get(rank, str(rank))
    return class_(rank_str, suit)
for c in [card_class(rank, suit) for rank in range(1, 14) for suit in (Club, Diamond, Heart, Spade)]:
    if c.points:
        print(c.rank, c.suit.symbol, c.points, sep=' | ')

Output:

A | ♣ | 11
A | ♦ | 11
A | ♥ | 11
A | ♠ | 11
7 | ♣ | 10
7 | ♦ | 10
7 | ♥ | 10
7 | ♠ | 10
J | ♣ | 3
J | ♦ | 3
J | ♥ | 3
J | ♠ | 3
Q | ♣ | 2
Q | ♦ | 2
Q | ♥ | 2
Q | ♠ | 2
K | ♣ | 4
K | ♦ | 4
K | ♥ | 4
K | ♠ | 4

Mapping to a tuple of values

Combining both lookups into a single dictionary of (class, rank_string) tuples:

def card_tuple(rank, suit):
    class_, rank_str = {
        1: (AceCard, 'A'),
        11: (FaceCard, 'J'),
        12: (FaceCard, 'Q'),
        13: (FaceCard, 'K'),
    }.get(rank, (NumberCard, str(rank)))
    return class_(rank_str, suit)
for c in [card_tuple(rank, suit) for rank in range(1, 14) for suit in (Club, Diamond, Heart, Spade)]:
    if c.points:
        print(c.rank, c.suit.symbol, c.points, sep=' | ')

Output: (same as above)

The partial function solution

functools.partial freezes leading arguments of a function (or class constructor), producing a callable with fewer parameters.

Reference: https://www.geeksforgeeks.org/partial-functions-python/

from functools import partial
 
# A normal function
def f(a, b, c, x):
    return 1000*a + 100*b + 10*c + x
 
# A partial function that calls f with a=3, b=1 and c=4
g = partial(f, 3, 1, 4)
 
# Calling g()
g(5)

Output:

3145

Applied to the card factory — each rank maps to a constructor pre-filled with its rank string:

from functools import partial
 
def card_partial(rank, suit):
    part_class = {
        1: partial(AceCard, 'A'),
        11: partial(FaceCard, 'J'),
        12: partial(FaceCard, 'Q'),
        13: partial(FaceCard, 'K'),
    }.get(rank, partial(NumberCard, str(rank)))
 
    return part_class(suit)
for c in [card_partial(rank, suit) for rank in range(1, 14) for suit in (Club, Diamond, Heart, Spade)]:
    if c.points:
        print(c.rank, c.suit.symbol, c.points, sep=' | ')

Output: (same as above)

Fluent APIs for factories

A fluent API returns self from each builder method, allowing chained calls such as cards.rank(r+1).suit(s) — the object-oriented equivalent of partial():

class CardFactory:
 
    def rank(self, rank):
        self.class_, self.rank_str = {
            1: (AceCard, 'A'),
            11: (FaceCard, 'J'),
            12: (FaceCard, 'Q'),
            13: (FaceCard, 'K'),
        }.get(rank, (NumberCard, str(rank)))
        return self  # fluent factory object (replaces partial())
 
    def suit(self, suit):
        return self.class_(self.rank_str, suit)
cards = CardFactory()
deck = [cards.rank(r+1).suit(s) for r in range(13) for s in (Club, Diamond, Heart, Spade)]
for c in deck:
    if c.points:
        print(c.rank, c.suit.symbol, c.points, sep=' | ')

Output: (same as above)

Inheritance and the super() call

Anti-pattern: implementing __init__() in each subclass

Bad: violates the DRY principle (Don't Repeat Yourself)

Every subclass repeats the suit/rank assignment logic; a change in Card must be copied into all subclasses.

class Card:
    pass
 
class NumberCard(Card):
    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = str(rank)
        if rank == 7:
            self.points = 10
        else:
            self.points = 0
 
class AceCard(Card):
    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = "A"
        self.points = 11
 
class FaceCard(Card):
    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = {11: 'Q', 12: 'J', 13: 'K'}[rank]
        self.points = {11: 3, 12: 4, 13: 5}[rank]

Good: initializer at the superclass level

Common state is initialized once in Card; subclasses call super().__init__() and only add their specific logic:

class Card:
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
        self.points = None
 
    def __repr__(self) -> str:
        return f'({self.rank}{self.suit.symbol},p{self.points})'
 
class NumberCard(Card):
    def __init__(self, rank, suit):
        super().__init__(str(rank), suit)
        if rank == 7:
            self.points = 10
        else:
            self.points = 0
 
class AceCard(Card):
    def __init__(self, rank, suit):
        super().__init__("A", suit)
        self.points = 11
 
class FaceCard(Card):
    def __init__(self, rank, suit):
        super().__init__({11: 'J', 12: 'Q', 13: 'K'}[rank], suit)
        self.points = {11: 3, 12: 4, 13: 5}[rank]
def card10(rank, suit):
    if rank == 1:
        return AceCard(rank, suit)
    elif 2 <= rank < 11:
        return NumberCard(rank, suit)
    elif 11 <= rank < 14:
        return FaceCard(rank, suit)
    else:
        raise Exception("Rank out of range")
for c in [card10(rank, suit) for rank in range(1, 14) for suit in (Club, Diamond, Heart, Spade)]:
    if c.points:
        print(c)

Output:

(A♣,p11)
(A♦,p11)
(A♥,p11)
(A♠,p11)
(7♣,p10)
(7♦,p10)
(7♥,p10)
(7♠,p10)
(J♣,p3)
(J♦,p3)
(J♥,p3)
(J♠,p3)
(Q♣,p4)
(Q♦,p4)
(Q♥,p4)
(Q♠,p4)
(K♣,p5)
(K♦,p5)
(K♥,p5)
(K♠,p5)

Composition

Simple composed objects

A composite object (also called a container) wraps other objects — here, a Deck that owns a shuffled list of cards:

import random
 
d = [card10(r+1, s) for r in range(13) for s in (Club, Diamond, Heart, Spade)]
random.shuffle(d)
hand = [d.pop(), d.pop()]
hand

Output:

[(Q♦,p4), (6♦,p0)]

Encapsulating the deck-building logic in a class:

class Deck:
    def __init__(self):
        self._cards = [card10(r+1, s) for r in range(13) for s in (Club, Diamond, Heart, Spade)]
        random.shuffle(self._cards)
 
    def pop(self):
        return self._cards.pop()
d = Deck()
hand = [d.pop(), d.pop()]
hand

Output:

[(9♥,p0), (A♠,p11)]

Extending a collection class

Deck2 inherits from list, so it is a deck of cards rather than having one — inheritance vs. composition in action:

class Deck2(list):
    def __init__(self, decks=1):
        super().__init__()
        for i in range(decks):
            self.extend(card10(r+1, s) for r in range(13) for s in (Club, Diamond, Heart, Spade))
            random.shuffle(self)
        burn = random.randint(1, 52)
        for i in range(burn):
            self.pop()
d = Deck2()
hand = [d.pop(), d.pop()]
hand

Output:

[(A♦,p11), (7♦,p10)]

Complex composite objects

A Hand aggregates cards and provides a points summary:

class Hand:
    def __init__(self):
        self.cards = []
 
    def bet(self):
        raise NotImplementedError("No bet method")
 
    def __repr__(self) -> str:
        return f'{self.cards} | points: {sum(c.points for c in self.cards)}'
d = Deck()
h = Hand()
h.cards.append(d.pop())
h.cards.append(d.pop())
h

Output:

[(10♠,p0), (A♦,p11)] | points: 11

Initialization with type validation

Assertions document preconditions on constructor arguments (note: assert statements are stripped when running with -O):

class Hand:
    def __init__(self, player: int):
        self.cards = []
        assert isinstance(player, int)
        self.player = player
 
    def bet(self):
        raise NotImplementedError("No bet method")
 
    def __repr__(self) -> str:
        return f'{[c for c in self.cards]} | points: {sum(c.points for c in self.cards)}'

Initialization, encapsulation, and privacy

The general Python policy regarding privacy can be summed up as: “we’re all adults here”.

  • Most names are public.
  • Names starting with _ are somewhat less public — use them for implementation details that are truly subject to change.
  • Names beginning and ending with __ are internal to Python. Never invent these; only use the names defined by the language reference.

Basic special methods

The format() method of a string can also access these methods: {!r} requests __repr__() and {!s} requests __str__().

class Hand:
    def __init__(self):
        self.cards = []
 
    def __repr__(self) -> str:
        return f'{__class__.__name__} {self.cards}'
 
    def __str__(self) -> str:
        return f'{self.cards}'
d = Deck()
h = Hand()
h.cards.append(d.pop())
h.cards.append(d.pop())
print(f'{h!r}')

Output:

Hand [(A♥,p11), (8♠,p0)]

The __new__ method

__new__ runs before __init__: it is the static method that actually creates and returns the instance, while __init__ only initializes the object that __new__ returned. The object is constructed by calling object.__new__(cls) (or a superclass’s __new__).

class TrackedCard:
    """Shows the division of labour between __new__ and __init__"""
 
    def __new__(cls, rank, suit):
        instance = super().__new__(cls)   # creation
        print(f'__new__: creating {cls.__name__}')
        return instance
 
    def __init__(self, rank, suit):
        print(f'__init__: initializing ({rank}{suit})')
        self.rank = rank
        self.suit = suit
 
    def __repr__(self) -> str:
        return f'({self.rank}{self.suit})'
c = TrackedCard('A', '\u2660')
c

Output:

__new__: creating TrackedCard
__init__: initializing (A♠)
(A♠)

Because __new__ controls creation itself, it enables patterns that __init__ alone cannot express. The classic example is the Singleton — only one Deck instance may ever exist, no matter how many times the class is called:

class SingletonDeck:
    """Only one deck instance is ever created"""
 
    _instance = None
 
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._cards = [card10(r+1, s) for r in range(13) for s in (Club, Diamond, Heart, Spade)]
            random.shuffle(cls._instance._cards)
        return cls._instance
 
    def pop(self):
        return self._cards.pop()
d1 = SingletonDeck()
d2 = SingletonDeck()
print(d1 is d2)
d1.pop()

Output:

True
(K♥,p5)

When to use __new__

Common legitimate uses: the Singleton pattern, subclassing immutable types (int, str, tuple) — whose values cannot be changed in __init__ — and controlling/denying instance creation. For most everyday classes, defining only __init__ is the right choice.

Hash methods

By default, object identity determines the hash:

h.__hash__()

Output:

7915461610863
x = object()
hash(x)

Output:

7915471400818
id(x)
id(x) // 16

Output:

7915471400818

Two separately constructed cards are distinct objects,

c1 = AceCard(1, Spade)
c2 = AceCard(1, Spade)
print(id(c1), id(c2))

Output:

126647384618848 126647384617216
c1 is c2

Output:

False
print(c1 == c2)  # BAD — logically they are equal

Output:

False

Equality methods

Implementing __eq__ (value equality) and a consistent __hash__ fixes this. Rule: objects that compare equal must have the same hash.

class Card2:
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
        self.points = None
 
    def __repr__(self) -> str:
        return f'({__class__.__name__} {self.__dict__}'
 
    def __eq__(self, other):
        return self.suit == other.suit and self.rank == other.rank
 
    def __hash__(self):
        return hash(self.suit) ^ hash(self.rank)
 
class AceCard2(Card2):
 
    def __init__(self, rank, suit):
        super().__init__("A", suit)
c1 = AceCard2(1, Spade)
c2 = AceCard2(1, Spade)
print(id(c1), id(c2))

Output:

126647383156496 126647384224192
print(hash(c1), hash(c2))

Output:

6237461651435174587 6237461651435174587
print(c1 == c2)

Output:

True

The comparison operator methods

Defining __lt__ gives the < operator a domain meaning — here, comparing players by hand points:

class Bisca:
 
    def __init__(self, player):
        self.deck = Deck()
        self.player = {'name': player, 'hand': Hand()}
 
    def draw(self):
        self.player['hand'].cards.append(self.deck.pop())
 
    def __lt__(self, other):
        return sum(c.points for c in self.player['hand'].cards) < sum(c.points for c in other.player['hand'].cards)
 
    def __repr__(self) -> str:
        return f'{self.player}'
manuel = Bisca('manuel')
morais = Bisca('morais')
manuel.draw()
morais.draw()
print(manuel, morais)

Output:

{'name': 'manuel', 'hand': Hand [(J♠,p3)]} {'name': 'morais', 'hand': Hand [(Q♥,p4)]}
manuel < morais

Output:

True

The __del__ method

__del__ runs when an object is garbage-collected — a good illustration of reference counting and shallow copies:

class Noisy:
    def __del__(self):
        print(f"Removing {id(self)}")
x = Noisy()
del x

Output:

Removing 126647384042288
# shallow copies
ln = [Noisy(), Noisy()]
ln2 = ln[:]
del ln
del ln2

Output:

Removing 126647384041136
Removing 126647384033648

Shallow copy semantics

ln[:] copies the list but not the elements. Deleting ln does not destroy the Noisy objects — ln2 still references them, so __del__ only fires when the last reference (ln2) is deleted.

Classmethod decorators

@classmethod receives the class (clf below) as its first argument, making it useful for polymorphic behaviour driven by class attributes:

class Unit:
    """Full name for the unit"""
 
    factor = 1.0
    standard = None
    name = ""
 
    @classmethod
    def value(clf, value):
        if value is None:
            return None
        return value / clf.factor
 
    @classmethod
    def convert(clf, value):
        if value is None:
            return None
        return value * clf.factor

Subclasses configure behaviour by overriding class attributes:

class INCH:
    pass
 
class MM:
    pass
 
class FOOT(Unit):
    """Feet"""
    name = "ft"
    standard = INCH
    factor = 1/12
 
class CENTIMETER(Unit):
    """Centimeters"""
    name = "cm"
    standard = MM
    factor = 10
cesar = FOOT.value(8)
CENTIMETER.convert(12)

Output:

120

Metaclass

a notion Python adopts from the Smalltalk language

Real-world examples:

  • Django — uses metaclasses to build ORM model classes from declarative fields.
  • SQLAlchemy — metaclasses create table mappings and query objects.
  • Pydantic — metaclasses generate model schema classes and validators.

Classes are objects too

In Python, a class is itself an object — and every object has a type. The type of a class is a metaclass.

class Foo:
    def bar(self):
        pass
 
foo_obj = Foo()
print("Type of Foo's instance is:", type(foo_obj))
print("Type of Foo is:", type(Foo))

Output:

Type of Foo's instance is: <class '__main__.Foo'>
Type of Foo is: <class 'type'>

Building a class at runtime with type()

The three-argument form of type creates classes — the signature is type(name, bases, dict):

Dummy = type("Dummy", (), {"var1": "hello world"})
dummy = Dummy()
print(dummy.var1)

Output:

hello world

A custom metaclass

Subclassing type lets you intercept class creation itself: __new__ builds the class dict, __init__ initializes the finished class.

class MyMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs['new_attribute'] = 'Hello, World!'
        attrs['new_method'] = lambda self: 'Hello from a new method!'
        return super().__new__(cls, name, bases, attrs)
 
    def __init__(self, name, bases, attrs):
        # perform any additional initialization here...
        super().__init__(name, bases, attrs)
class MyClass(metaclass=MyMeta):
    pass
 
obj = MyClass()
print(obj.new_attribute)  # 'Hello, World!'
print(obj.new_method())  # 'Hello from a new method!'

Output:

Hello, World!
Hello from a new method!

Metaclass vs class-level attribute

The same result is achievable with a class decorator or by plain inheritance. Rule of thumb: use a metaclass only when you must change how classes are constructed — API validation, field collection, auto-registration. Otherwise a decorator is simpler and easier to read.

Connect the dots

You already used a metaclass feature in PY51-python-classes-intro: type(temperature) != float in the Celsius setter, and class-level constants like USD_RATE live in the class object — the very object that type() builds and metaclasses customize.

Exercise 1 — Offline Dino Runner

Concepts: inheritance, super(), method overriding, polymorphism

Scenario: Recreate the little T-Rex game that appears in Chrome when your internet is down. The dino runs automatically, and the player has to jump over cacti and duck under birds. You can build it as a text-based game (one frame per loop iteration, printed to the console) or with pygame if you want graphics.
https://trex-runner.com/

Tasks

  1. Create a base class GameObject with x, y, width, height, and methods update() and collides_with(other). The collision check can be a simple rectangle overlap.
  2. Create a Dino(GameObject) subclass. Its __init__ calls super().__init__() and adds is_jumping, is_ducking, and velocity_y. Add jump() and duck() methods. Override update() so it applies gravity, but call super().update() first.
  3. Create an Obstacle(GameObject) class that moves left every frame using a speed attribute. Then create subclasses:
    • Cactus: ground level, with a size ("small" or "large") that changes its height.
    • Bird: flying at one of two heights; the dino must duck under it. Each frame it also flaps its wings (animate it by cycling through two sprites/frames).
  4. Both subclasses override update() to add their own behavior, calling super().update() for the shared leftward movement.
  5. Write a Game class with a run() loop that keeps a list of obstacles and calls update() on all of them without checking their type (no isinstance in the game loop!). Spawn new obstacles at random. The game ends when dino.collides_with(obstacle) is True.

Bonus: score one point per obstacle that passes the dino; speed the game up every N points.

Hints

Hints

  • Rectangle collision — two axis-aligned rectangles overlap when both intervals overlap on each axis:
    x1 < x2 + w2 and x2 < x1 + w1 and y1 < y2 + h2 and y2 < y1 + h1
    (write it as not no_overlap if that reads easier).
  • Gravity — each frame: velocity_y += GRAVITY, then y += velocity_y; clamp y back to ground level and set is_jumping = False when the dino lands. Jumping is just velocity_y = -JUMP_FORCE.
  • Ducking — make the dino shorter (height // 2) and keep its bottom edge on the ground: adjust y when the height changes, not only the height.
  • super() discipline — the rule from this chapter: shared behavior lives in the superclass, subclasses add to it. Obstacle.update() moves left; Bird.update() calls super().update() then flaps. If you copy-paste the movement code into the subclass, you are doing it wrong.
  • Polymorphism — the game loop should be for obj in self.objects: obj.update() and collides_with() should work on any two GameObjects. That is the point of the exercise: the game never needs to know whether an object is a Cactus, Bird or Dino.
  • Spawning — random.choice([Cactus, Cactus, Bird]) gives cacti twice as often as birds; also randomize the gap between spawns (random.randint(MIN_GAP, MAX_GAP) frames).
  • Text rendering — pick a world width (e.g. 60 columns) and draw each object as a symbol (🦖, 🌵, 🦅) at its x position each frame. A simple print("\n" * 20) before each frame is enough to fake screen clearing.

Think before you code

Why does Bird inherit from Obstacle rather than from GameObject directly? What does each level of the hierarchy contribute?

Step-by-step solution

The solution builds the class hierarchy bottom-up. Run it with python dino.py and press j (jump) / d (duck) each frame, or just watch the demo loop.

Step 1 — the base class

GameObject holds position/size and knows how to test overlap against any other GameObject. Note that update() here is a no-op: subclasses are expected to override it.

import random
 
class GameObject:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
 
    def update(self):
        """Advance one frame. Subclasses override this."""
        pass
 
    def collides_with(self, other):
        """Axis-aligned rectangle overlap."""
        return (
            self.x < other.x + other.width
            and other.x < self.x + self.width
            and self.y < other.y + other.height
            and other.y < self.y + self.height
        )

Step 2 — the dino

Dino adds its own state and delegates shared setup to super().__init__(). Gravity lives in the overridden update(), and the ground check uses the current height so ducking (shorter dino) works for free.

class Dino(GameObject):
    GRAVITY = 0.8
    JUMP_FORCE = -12
    GROUND_Y = 20  # y of the ground line
 
    def __init__(self, x=5):
        # bottom edge sits on the ground; standing height = 4
        super().__init__(x, self.GROUND_Y - 4, 3, 4)
        self.is_jumping = False
        self.is_ducking = False
        self.velocity_y = 0
 
    def jump(self):
        if not self.is_jumping:
            self.is_jumping = True
            self.velocity_y = self.JUMP_FORCE
 
    def duck(self):
        if not self.is_ducking and not self.is_jumping:
            self.is_ducking = True
            self.height //= 2          # shorter...
            self.y = self.GROUND_Y - self.height  # ...but still on the ground
 
    def stand_up(self):
        if self.is_ducking:
            self.is_ducking = False
            self.y -= self.height      # restore height, keep bottom edge fixed
            self.height *= 2
 
    def update(self):
        super().update()               # hook for shared base behavior
        if self.is_jumping:
            self.velocity_y += self.GRAVITY
            self.y += self.velocity_y
            if self.y >= self.GROUND_Y - self.height:   # landed
                self.y = self.GROUND_Y - self.height
                self.is_jumping = False
                self.velocity_y = 0

Step 3 — obstacles and subclasses

Obstacle owns the shared leftward movement. Each subclass only configures itself in __init__ and adds behavior in update() — the movement code exists exactly once, in the superclass.

class Obstacle(GameObject):
    def __init__(self, x, y, width, height, speed=1.0):
        super().__init__(x, y, width, height)
        self.speed = speed
 
    def update(self):
        self.x -= self.speed           # shared: everything drifts left
 
 
class Cactus(Obstacle):
    def __init__(self, x, size="small"):
        height = 3 if size == "small" else 5
        width = 2 if size == "small" else 3
        super().__init__(x, Dino.GROUND_Y - height, width, height)
 
 
class Bird(Obstacle):
    def __init__(self, x, high=True):
        y = Dino.GROUND_Y - 8 if high else Dino.GROUND_Y - 4
        super().__init__(x, y, 3, 2, speed=1.5)   # birds are faster
        self.frame = 0
 
    def update(self):
        super().update()               # shared movement from Obstacle
        self.frame += 1                # then add our own: wing flap

Step 4 — the game loop

The game loop treats every object uniformly: it calls update() and collides_with() and never asks what it is. That is polymorphism doing the work — you can add a new obstacle type later without touching Game.

class Game:
    WIDTH = 60
 
    def __init__(self):
        self.dino = Dino()
        self.obstacles = []
        self.frames_to_spawn = 10
        self.score = 0
 
    def spawn(self):
        cls = random.choice([Cactus, Cactus, Bird])   # cacti more common
        self.obstacles.append(cls(self.WIDTH))
 
    def run(self, frames=60):
        for _ in range(frames):
            self.frames_to_spawn -= 1
            if self.frames_to_spawn <= 0:
                self.spawn()
                self.frames_to_spawn = random.randint(8, 20)
 
            self.dino.update()
            for obstacle in self.obstacles:           # no isinstance anywhere
                obstacle.update()
                if self.dino.collides_with(obstacle):
                    self.draw(game_over=True)
                    return self.score
            self.obstacles = [o for o in self.obstacles if o.x + o.width > 0]
            self.score += 1
            self.draw()
        return self.score
 
    def draw(self, game_over=False):
        screen = ["."] * self.WIDTH
        for o in self.obstacles:
            col = round(o.x)
            screen[col] = "🦅" if isinstance(o, Bird) else "🌵"   # ok here: rendering, not logic
        screen[round(self.dino.x)] = "🦖"
        print("\n" * 15, "".join(screen), f"score={self.score}",
              "GAME OVER" if game_over else "", sep="\n")
 
 
if __name__ == "__main__":
    Game().run()

Where each concept shows up

  • Inheritance — Dino, Obstacle inherit from GameObject; Cactus, Bird from Obstacle.
  • super() — every __init__ and every overridden update() delegates shared work up the chain; behavior is never duplicated.
  • Method overriding — Dino.update(), Bird.update() extend the base behavior by calling super().update() first, then adding their own.
  • Polymorphism — Game.run() iterates a mixed list of objects and relies only on the GameObject interface (update(), collides_with()).

Stretch goals

  • Add a Coin obstacle worth points (it despawns on collision instead of ending the game) — notice Game still needs no changes if you model “despawn” inside the object.
  • Wire real keyboard input with msvcrt (Windows) / termios (Linux) or switch to pygame: Game should not change at all, only Dino gains an input handler.
  • Refactor collides_with to use __le__/__ge__ special methods from this chapter — can intervals compare themselves?