๐ŸงฌInheritance, super(), MROLESSON

Inheritance, super(), and Method Resolution Order

Inheritance lets a class inherit attributes and methods from another class. This enables code reuse and expresses "is-a" relationships: a Dog is an Animal, a SavingsAccount is a BankAccount.

Single Inheritance

The subclass (Dog) gets all of the parent's (Animal) methods for free. It can also define its own additional methods.

super().init() โ€” Delegating to the Parent

When a subclass has its own __init__, it should call the parent's __init__ using super() to ensure the parent's setup is done correctly.

If you forget super().__init__(), the parent's attributes won't be set and you'll get AttributeError when you try to access them.

Method Overriding

A subclass can override any method from its parent by defining a method with the same name:

Extending vs Replacing

You can call the parent's method and extend its behavior:

isinstance() and issubclass()

Multiple Inheritance

Python supports inheriting from multiple parent classes:

MRO: Method Resolution Order

When Python looks up a method, it follows the Method Resolution Order (MRO) โ€” a deterministic ordering of classes to search. Use __mro__ or mro() to inspect it:

The MRO is computed using the C3 linearization algorithm, which ensures:

  1. Subclasses come before parent classes
  2. The left-to-right order of base classes is preserved
  3. No class appears before any of its subclasses

super() in Multiple Inheritance

super() follows the MRO, not just the direct parent. This is why super().__init__() is the correct way to call parent constructors in all cases:

Each super().__init__() call follows the MRO, ensuring A.__init__ is called exactly once. This pattern is called cooperative multiple inheritance.

Mixins

A mixin is a class that provides methods to other classes through inheritance, but is not meant to stand alone. Mixins are a clean way to add behavior without deep inheritance hierarchies:

Mixins keep related behavior grouped in one place, and you can mix and match them across unrelated class hierarchies.

Knowledge Check

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

Given `class D(B, C)` where both B and C inherit from A, in what order does Python's MRO place these classes?

What is a mixin in Python?