L4·OOP & Errors

🧬Inheritance & MRO

Class hierarchies and method resolution order.

inheritancesuperMRO

§ 1Subclass

class Child(Parent): overrides methods and adds new ones. super() calls the parent's version.

§ 2Multiple inheritance

class C(A, B): — Python uses C3 linearization to compute MRO. Inspect via C.__mro__.

§ 3isinstance / issubclass

Runtime checks against a class or tuple of classes.

Example

1class Animal:
2 def speak(self): return "?"
3
4class Dog(Animal):
5 def speak(self): return "woof"
6
7class Puppy(Dog):
8 def speak(self): return super().speak() + "!"
9
10print(Puppy().speak()) # woof!
11print([c.__name__ for c in Puppy.__mro__])

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
What does super() do?