Python 101Free
CLASSES AND OOP

Inheritance

Building new classes on top of existing ones.

SECTION 01

Subclassing and override

A subclass declares a new class based on another. class Puppy(Dog): says "a Puppy is a kind of Dog". The subclass inherits every attribute and method that the parent defined.

If you define a method in the subclass with the same name as one in the parent, the subclass version wins. This is called overriding. The instance still has access to the rest of the parent's methods, just not the one that got replaced.

Use inheritance to express "is a" relationships, where the subclass is genuinely a specialized version of the parent. Avoid using it for code reuse alone; composition (one object owning another) usually works better when the relationship is "has a".

python
class Puppy(Dog):
    def bark(self):                       # override
        return f"{self.name} yips"

Puppy("Mia").bark()   # 'Mia yips'
SECTION 02

super and the MRO

super() inside a subclass method calls the parent's version. The classic use is in __init__, where you want to set up parent state before adding the subclass-specific bits. super().__init__(name) runs Dog.__init__(self, name) and then control returns to your code.

The Method Resolution Order is the linear list Python uses to decide "which parent comes next?". For single inheritance the answer is obvious. For multiple inheritance Python uses the C3 linearization algorithm, which produces a deterministic order even when the inheritance graph is a diamond.

Most code only inherits from one class at a time, so the MRO is invisible. When you do mix in multiple parents, run Class.mro() to see exactly what order super() will walk. The output is the truth.

python
class Service:
    def __init__(self, name):
        self.name = name

class TimedService(Service):
    def __init__(self, name, timeout):
        super().__init__(name)   # set up parent state first
        self.timeout = timeout
← PREVIOUS
Classes and Instances
NEXT →
Dunder Methods