What is multilevel inheritance in Python with example?

Multilevel inheritance in Python involves deriving a class from another class, which in turn is derived from yet another class.

This creates a chain of inheritance, allowing the subclass to inherit properties and methods not only from its immediate parent class but also from the parent class’s ancestors, forming a hierarchical relationship.

This enables a hierarchical organization of classes and promotes code reusability.

Let’s illustrate multilevel inheritance with an example:

# Base class (also known as the parent class)
class Animal:
    def __init__(self, species):
        self.species = species

    def make_sound(self):

# Intermediate class (child of Animal)
class Mammal(Animal):
    def __init__(self, species, sound):
        self.sound = sound

    def make_sound(self):
        return f"{self.species} makes {self.sound} sound."

# Derived class (child of Mammal)
class Dog(Mammal):
    def __init__(self, breed, sound):
        super().__init__("Dog", sound)
        self.breed = breed

    def make_sound(self):
        return f"{self.breed} dog says {self.sound}."

# Create an instance of the Dog class and demonstrate multilevel inheritance
my_dog = Dog("Golden Retriever", "Woof")

print(my_dog.make_sound())  # Output: "Golden Retriever dog says Woof."
Code language: Python (python)

In this example, we have three classes: Animal, Mammal, and Dog. The Animal class is the base class that provides a basic structure for all animals.

The Mammal class is derived from Animal and adds additional attributes and a method.

Finally, the Dog class is derived from Mammal, inheriting attributes from both Mammal and Animal. The make_sound() method is overridden at each level to provide specific behavior for each class.

As a result, when we create an instance of the Dog class and call the make_sound() method, it will display the message with the breed of the dog and the sound it makes, showcasing the multilevel inheritance in action.

Read More;

  • Yaryna Ostapchuk

    I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

Leave a Comment