Lesson 25 / 47

Inheritance & Overriding

Build a new class on top of an existing one, and customize behaviour.

Extending a class

A subclass gets everything from its parent and can add or override methods. super() calls the parent's version.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return f"{self.name} makes a sound"

class Dog(Animal):
    def speak(self):                 # override
        base = super().speak()
        return f"{base}: Woof!"

print(Dog("Rex").speak())

MRO in brief

Python supports multiple inheritance and checks method lookup via the MRO (Method Resolution Order) — but single inheritance covers most real code.