Python theorytheory 0/50 · 0%
OOP · medium

24. Inheritance and polymorphism

Subclassing, method overriding, and super().

A class inherits from a base class by listing it in parentheses, gaining its attributes and methods, and may override any of them.

python
class Token:
    def __init__(self, symbol):
        self.symbol = symbol
    def describe(self):
        return f"Token({self.symbol})"

class StableCoin(Token):
    def __init__(self, symbol, peg):
        super().__init__(symbol)
        self.peg = peg
    def describe(self):
        return f"{super().describe()} pegged to {self.peg}"

`super()` calls the parent implementation, which is important when overriding `__init__` so the base class still initializes correctly. Python supports multiple inheritance, resolved via the Method Resolution Order (MRO).

Check your understanding

  1. 1. What does `super().__init__(symbol)` do in a subclass?

  2. 2. What determines the order classes are searched in multiple inheritance?

  3. 3. What is polymorphism illustrated by in the example?