Multilevel inheritance is a type of inheritance where a class is derived from another class, which in turn is derived from another class. This forms a chain of inheritance, with each class inheriting properties and behaviors from its predecessor.
Multilevel inheritance helps to:
Let’s look at a practical example to understand multilevel inheritance better.
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
class Mammal(Animal):
def walk(self):
print(f"{self.name} is walking")
class Dog(Mammal):
def bark(self):
print(f"{self.name} says Woof!")
if __name__ == "__main__":
my_dog = Dog("Buddy")
my_dog.eat() # Output: Buddy is eating
my_dog.walk() # Output: Buddy is walking
my_dog.bark() # Output: Buddy says Woof!
Animal:
__init__ method initializes the name attribute.Mammal:
name attribute and eat method from the Animal class.Dog:
name attribute, eat method, and walk method from the Mammal class.Dog that prints a barking sound.In multilevel inheritance, Python uses the Method Resolution Order (MRO) to determine the order in which methods should be inherited and called. The MRO follows a depth-first, left-to-right approach in a multilevel inheritance scenario.
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
class C(B):
def show(self):
print("C")
# MRO: C -> B -> A -> object
c = C()
c.show() # Output: C
Here, the show method of class C is called because C overrides the show method of B, which in turn overrides the show method of A.