Multi-Level Inheritance
Explore multi-level inheritance in Python by understanding how classes inherit from parent classes in a chain. Learn to implement inheritance hierarchies, override methods, and access superclass methods, building a foundational grasp of class behavior.
We'll cover the following...
Introduction
In addition to single-level inheritance, Python also supports multi-level inheritance. This means that you can create a hierarchy of classes, each inheriting from its superclass. The following figure illustrates an example of multi-level inheritance.
The following hierarchy is clear from the above figure:
| Class | Superclass | Relation |
|---|---|---|
| Carnivore | Mammal | Carnivore is a Mammal |
| Mammal | Animal | Mammal is an Animal |
| Animal | - | - |
Implementation
Syntactically, multi-level inheritance in Python is quite similar to single-level inheritance. Consider the following basic code snippet:
However, if we move the print method in a separate method, the subclass can not only access the method of its parent class—but also override it if needed. This behavior is shown in the highlighted lines of the following code:
Now if you remove the printer() method of the Carnivore class in lines 18, 19, the lion object will be able to access the printer() method of its super/parent class Mammal. The output will then become:
I am warm blooded.
If you also remove the printer() method in 12, 13 of the Mammal class, the lion object will access the printer() method of its superclass Animal. It will then print:
I am a lion.
In the next lesson, we will discuss multiple inheritance; it’s slightly different from multi-level inheritance.