Types of Inheritance
Explore the five key types of inheritance in Python object-oriented programming. Understand how parent and child classes relate through single, multi-level, hierarchical, multiple, and hybrid inheritance. Gain the skills to implement these inheritance types using practical code examples to improve code reusability and structure.
We'll cover the following...
Based upon parent classes and child classes, there exists the following five types of inheritance:
- Single
- Multi-level
- Hierarchical
- Multiple
- Hybrid
Single inheritance
In single inheritance, there is only a single class extending from another class. We can take the example of the Vehicle class as the parent class, and the Car class as the child class. Let’s implement these classes below:
Multi-level inheritance
When a class is derived from a class which itself is derived from another class, it is called multilevel inheritance. We can extend the classes to as many levels as we want to.
Let’s implement the three classes illustrated above:
- A
CarIS AVehicle - A
HybridIS ACar
Hierarchical inheritance
In hierarchical inheritance, more than one class extends, as per the requirement of the design, from the same base class. The common attributes of these child classes are implemented inside the base class.
Example:
- A
CarIS AVehicle - A
TruckIS AVehicle
Below is a code example of hierarchical inheritance.
Multiple inheritance
When a class is derived from more than one base class, i.e., when a class has more than one immediate parent class, it is called multiple inheritance.
Example:
HybridEngineIS AElectricEngine.HybridEngineIS ACombustionEngineas well.
Below is a code example of multiple inheritance.
Hybrid inheritance
A type of inheritance which is a combination of Multiple and Multi-level inheritance is called hybrid inheritance.
CombustionEngineIS AEngine.ElectricEngineIS AEngine.HybridEngineIS AElectricEngineand aCombustionEngine.
Below is the code implementation of an example of hybrid inheritance.