In this Python oops program, we will show multilevel inheritance example in multiple classes. This example demonstrates the concept of class inheritance and method overriding in Python.
Multilevel Inheritance Example
Steps to solve the program
- Five classes (Class1, Class2, Class3, Class4, and Class5) are defined. Each class is derived from its respective parent class, forming an inheritance hierarchy.
- Each class has a single method that prints a specific message.
- An object (obj) of the final class, Class5, is created.
- By creating an instance of Class5, we have access to all the methods defined in Class5, as well as the methods inherited from its parent classes (Class4, Class3, Class2, and Class1).
- The methods are called using dot notation on the obj object.
class Class1:
def method1(self):
print("Method 1 of Class 1")
class Class2(Class1):
def method2(self):
print("Method 2 of Class 2")
class Class3(Class2):
def method3(self):
print("Method 3 of Class 3")
class Class4(Class3):
def method4(self):
print("Method 4 of Class 4")
class Class5(Class4):
def method5(self):
print("Method 5 of Class 5")
# Create an object of the final class and access methods
obj = Class5()
obj.method1()
obj.method2()
obj.method3()
obj.method4()
obj.method5()
Output:
Method 1 of Class 1
Method 2 of Class 2
Method 3 of Class 3
Method 4 of Class 4
Method 5 of Class 5
Related Articles
Set Instance variable data with setattr and getattr methods.
Python oops program with encapsulation.
Create a Python class called Rectangle with attributes length and width.
Create a Python class called Circle with attributes radius.
Create a Python class called Person with attributes name and age.
Create a Python class called Student that inherits from the Person class.