Skip to main content

Object-Oriented Python

Inheritance and Composition

0:00
LearnStep 1/3

Building Robust Class Hierarchies

Python offers powerful Object-Oriented features, but misusing them can lead to brittle code. The choice between inheritance ("is-a") and composition ("has-a") is critical.

1. The Power of super()

The super() built-in function is the idiomatic way to access inherited methods. It dynamically delegates method calls to classes in the parent chain, crucial for cooperative multiple inheritance.

python

2. Method Resolution Order (MRO)

Python uses the C3 linearization algorithm to determine the order in which base classes are searched. You can inspect this order using the __mro__ attribute.

python

3. Composition Over Inheritance

Inheritance locks you into a rigid hierarchy. Composition involves building classes by combining objects of other classes. This offers greater flexibility.

python

4. Abstract Base Classes (ABCs)

When you do need inheritance to define an interface, use the abc module. This enforces that subclasses implement specific methods.

python