Multilevel Inheritance in Python (with Example)
When a class is derived from a class which is also derived from another class, it is called multilevel inheritance in Python.
In multilevel inheritance, a child class becomes a parent class for another child class, which accesses all the properties and methods of both classes.
In other words, each class inherits attributes and methods from its immediate parent class, which in turn inherit from another parent class.
Python does not restrict the number of levels at which we will get multilevel inheritance. We can do inheritance (i.e. parent-child relationships) on any number of levels. It is not bound with only three levels, as shown in the below figure.
The difference between a single level inheritance and multilevel inheritance is that single inheritance involves a class inheriting from a single parent class, while multilevel inheritance involves a chain of inheritance with each class inheriting from its immediate parent class.
Syntax to Define Multilevel Inheritance in Python
The syntax for multilevel inheritance in Python is as follows:
class Class1:
# Class1 class attributes and methods
class Class2(Class1):
# Class2 class attributes and methods
# Inherits from Class1
class Class3(Class2):
# Class3 class attributes and methods
# Inherits from Class2, which in turn inherits from Class1
# Continue this pattern for as many classes as needed.
class ClassN(ClassN_minus_1):
# ClassN class attributes and methods
# Inherits from the previous class in the chain (ClassN_minus_1)
In this syntax:
- Class1 is the top-level class.
- Class2 inherits from Class1, creating a parent-child relationship.
- Class3 inherits from Class2, creating a multilevel inheritance chain.
You can continue this pattern for as many classes (Class4, Class5, and so on) as needed, with each class inheriting from the one immediately preceding it.
This syntax correctly establishes a multilevel inheritance hierarchy in Python, where each child class inherits the attributes and methods of its immediate parent class in the chain.
Simple Multilevel Example Programs
Let’s take some simple example programs based on the concept of multilevel inheritance in Python which you must practice to clear the concept.
Example 1:
# Python program to demonstrate multilevel inheritance up to three levels.
class Grandparent:
def grandparent_method(self):
print("This is a grandparent class method")
class Parent(Grandparent):
def parent_method(self):
print("This is a parent class method")
class Child(Parent):
def child_method(self):
print("This is a child class method")
# Create an instance of the Child class
child_obj = Child()
# Access methods from all levels of inheritance
child_obj.grandparent_method()
child_obj.parent_method()
child_obj.child_method()
Output:
This is a grandparent class method
This is a parent class method
This is a child class method
In this example program, we have created three classes: Grandparent, Parent, and Child. The Child class inherits from the Parent class, which in turn inherits from the Grandparent class. This is a classic example of multilevel inheritance.
When we create an instance of the Child class and, we can call and access methods from all levels of inheritance. The output will display messages from the Grandparent, Parent, and Child classes, showing that each class retains methods of its parent classes.
Example 2:
# Python program to demonstrate multilevel inheritance up to three levels.
class A:
def showMe(self):
print("I am class A")
class B(A):
def showMe2(self):
print("I am class B")
class C(B):
def showMe3(self):
print("I am class C")
# Create an instance of the class C.
c = C()
# Access methods from all levels of inheritance
c.showMe()
c.showMe2()
c.showMe3()
# Create an instance of class B.
b = B()
# Access methods from two levels of inheritance.
b.showMe()
b.showMe2()
# Create an instance of class A.
a = A()
# Access methods from first level of inheritance only.
a.showMe()
Output:
I am class A
I am class B
I am class C
I am class A
I am class B
I am class A
Advanced Multilevel Example for Best Practice
Let’s take some advanced example programs based on the concept of multilevel inheritance for the best practice.
Example 3:
# Define the top-level class GrandParent
class GrandParent(object):
# Constructor for GrandParent class, takes a name parameter.
def __init__(self, name):
self.name = name # Initialize the 'name' attribute
# Method to get the name.
def getName(self):
return self.name
# Define the Parent class, which inherits from GrandParent.
class Parent(GrandParent):
# Constructor for Parent class, takes name and age parameters.
def __init__(self, name, age):
# Call the constructor of the parent class (GrandParent)
GrandParent.__init__(self, name)
self.age = age # Initialize the 'age' attribute
# Method to get the age.
def getAge(self):
return self.age
# Define the Child class, which inherits from Parent.
class Child(Parent):
# Constructor for Child class, takes name, age, emp_id, and salary parameters.
def __init__(self, name, age, emp_id, salary):
# Call the constructor of the immediate parent class (Parent)
Parent.__init__(self, name, age)
self.emp_id = emp_id # Initialize the 'emp_id' attribute
self.salary = salary # Initialize the 'salary' attribute
# Method to get the employee ID.
def getEmp_Id(self):
return self.emp_id
# Method to get the salary.
def getSalary(self):
return self.salary
# Create an instance of the Child class by passing argument values.
child = Child("Mahikaa", 24, 23455, 90000)
# Print the name, age, employee id, and salary by calling methods on the 'child' object.
print(child.getName(), child.getAge(), child.getEmp_Id(), child.getSalary())
Output:
Mahikaa 24 23455 90000
This code is an example of multilevel inheritance in Python, where we have created three classes: GrandParent, Parent, and Child.
The GrandParent class is the top-level class in this hierarchy. It has a constructor method __init__() that takes a name parameter and initializes an instance variable self.name with the provided name. It also contains a method getName() that returns the value of self.name.
The Parent class inherits from the GrandParent class. Its constructor __init__() takes two parameters: name and age. Then, we have called the constructor of the parent class (GrandParent) using GrandParent.__init__(self, name) to initialize the name attribute inherited from GrandParent. We have also initialized its own attribute self.age with the provided age. The getAge() method returns the value of self.age.
The Child class inherits from the Parent class. Its constructor __init__() takes four parameters: name, age, emp_id, and salary.
Then, we have called the constructor of its immediate parent class (Parent) using Parent.__init__(self, name, age) to initialize the name and age attributes inherited from Parent.
We have also initialized its own attributes self.emp_id and self.salary with the provided values. The getEmp_Id method returns the value of self.emp_id, and getSalary returns the value of self.salary.
At last, we have created an instance of the Child class by passing argument values “Mahikaa” for name, 24 for age, 23455 for emp_id, and 90000 for salary. The print statement displays the values obtained by calling methods on the child object. So, when you run this code, it prints out the name, age, employee ID, and salary associated with that instance.
More Advanced Example Program
Let’s explore a more advanced example of multilevel inheritance in Python. In this example, we’ll create a hierarchy of classes representing different types of vehicles, starting from a basic Vehicle class and extending it to more specialized classes like Car and Motorcycle. Each class will inherit properties and methods from its parent class, showcasing how multilevel inheritance works.
Example 4:
# Define a base class named vehicle.
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start_engine(self):
print(self.make + " " + self.model + "'s engine is now running.")
# Child class (Car) inheriting from the parent class (Vehicle).
class Car(Vehicle):
def __init__(self, make, model, doors):
super().__init__(make, model)
self.doors = doors
def honk_horn(self):
print(self.make + " " + self.model + "'s horn goes 'Honk! Honk!'")
# Child class (SportsCar) inheriting from the parent class (Car).
class SportsCar(Car):
def __init__(self, make, model, doors, top_speed):
super().__init__(make, model, doors)
self.top_speed = top_speed
def show_info(self):
print("This is a " + self.make + " " + self.model + " sports car with " + str(self.doors) + " doors.")
print("It can reach a top speed of " + str(self.top_speed) + " mile per hour.")
# Child class (Motorcycle) inheriting from the parent class (Vehicle).
class Motorcycle(Vehicle):
def __init__(self, make, model, has_kickstand):
super().__init__(make, model)
self.has_kickstand = has_kickstand
def display_kickstand_status(self):
if self.has_kickstand:
print(self.make + " " + self.model + " has a kickstand.")
else:
print(self.make + " " + self.model + " does not have a kickstand.")
# Create instances of the classes
car = Car("Toyota", "Camry", 4)
sports_car = SportsCar("Ferrari", "488 GTB", 2, 205)
motorcycle = Motorcycle("Harley-Davidson", "Sportster", True)
# Demonstrate multilevel inheritance
car.start_engine()
car.honk_horn()
sports_car.start_engine()
sports_car.honk_horn()
sports_car.show_info()
motorcycle.start_engine()
motorcycle.display_kickstand_status()
Output:
Toyota Camry's engine is now running.
Toyota Camry's horn goes 'Honk! Honk!'
Ferrari 488 GTB's engine is now running.
Ferrari 488 GTB's horn goes 'Honk! Honk!'
This is a Ferrari 488 GTB sports car with 2 doors.
It can reach a top speed of 205 mph.
Harley-Davidson Sportster's engine is now running.
Harley-Davidson Sportster has a kickstand.
In this advanced example, we have a base class Vehicle with attributes like make and model and a method start_engine. The Car class inherits from Vehicle and adds the doors attribute and a method honk_horn.
The SportsCar class further inherits from Car and includes a top_speed attribute and a method show_info. The Motorcycle class also inherits from Vehicle and introduces a has_kickstand attribute and a method display_kickstand_status. We create instances of these classes and demonstrate how each class inherits and extends the functionality of its parent class.
Advantages of Multilevel Inheritance in Python
Multilevel inheritance in Python is a powerful feature that allows us to create a well-organized and reusable code. There are the following advantages of using multilevel inheritance that are as:
- Multilevel inheritance allows us to reuse code from multiple parent classes, reducing redundancy in the code.
- By breaking down our complex code into smaller, logically related classes, we can manage and maintain each class separately. This makes our code structure more manageable and easier to understand.
- With multilevel inheritance, we can organize classes in a hierarchical manner, making the code easier to understand and also improves readability.
When to Use Multilevel Inheritance
Multilevel inheritance is suitable when you have a clear hierarchy of classes where each child class inherits and extends the functionality of its parent classes. Use it when it logically makes sense in your program.
In this tutorial, we have discussed multilevel inheritance in Python with the help of various example programs. Hope that you will have understood the basic concept of multilevel inheritance and practiced all programs. Stay tuned with the next tutorial where we will learn about multiple inheritance in Python with the help of various advanced example programs for the best practice.
Thanks for reading!!!







