Python Multilevel Inheritance
Multilevel inheritance is a type of class hierarchy in object-oriented programming (OOP) where a class inherits from a derived class, forming a chain of inheritance. Each level passes down methods and properties, enabling cumulative specialization and reuse.
In Python, multilevel inheritance allows a subclass to indirectly inherit members from a grandparent class through its parent.
Syntax
class BaseClass:
# Base class code
class IntermediateClass(BaseClass):
# Inherits from BaseClass
class DerivedClass(IntermediateClass):
# Inherits from IntermediateClass
Here:
BaseClass: The top-most class in the hierarchy.IntermediateClass: Inherits fromBaseClass.DerivedClass: Inherits fromIntermediateClass, and indirectly fromBaseClass.
Example
In this example, the Dog class inherits from Animal, which in turn inherits from LivingBeing, allowing it to access methods from both ancestor classes:
class LivingBeing:def breathe(self):return "Breathing"class Animal(LivingBeing):def move(self):return "Moving"class Dog(Animal):def bark(self):return "Barking"dog = Dog()print(dog.breathe()) # Inherited from LivingBeingprint(dog.move()) # Inherited from Animalprint(dog.bark()) # Defined in Dog
The output of this code is:
BreathingMovingBarking
This example forms a chain:
Dog→Animal→LivingBeing- The
Dogclass gains all the methods of its parent and grandparent.
Visual representation of multilevel inheritance:
+--------------+
| LivingBeing |
|--------------|
| breathe() |
+------+-------+
|
▼
+--------------+
| Animal |
|--------------|
| move() |
+------+-------+
|
▼
+--------------+
| Dog |
|--------------|
| bark() |
+--------------+
Codebyte Example
In this codebyte example, the Laptop class inherits features from Computer and Device, demonstrating how functionality accumulates across multiple levels of inheritance:
Benefits and Best Practices of Multilevel Inheritance
- Promotes structured layering of functionality.
- Each derived class builds upon its predecessor.
- Useful when deeper specialization is logically needed.
- Helps organize code when behaviors evolve level by level.
Note: Avoid deep inheritance chains when possible, as too many layers can make debugging and maintenance harder.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours