Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance,Encapsulation,Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python.
Pre-Requisite
Python Multilevel Inheritance
MultilevelInheritance in Python is a type of Inheritance in which a class inherits from a class, which itself inherits from another class. It allows a class to inherit properties and methods frommultiple parent classes, forming a hierarchy similar to a family tree. It consists of two main aspects:
- Base class: This represents a broad concept.
- Derived classes: These inherit from the base class and add specific traits.
Diagram for Multilevel Inheritance in Python
Multilevel Inheritance in PythonBelow are some of the examples by which we can understand more about multilevel inheritance inPython:
Example 1: Simple Multilevel Inheritance
In this method, we have three different classes that isBase, Intermediate and derived,and we have inherited the feature of Base to Intermediate and then the feature of Intermediate to derived class.
Python3classBase:# Constructor to set Datadef__init__(self,name,roll,role):self.name=nameself.roll=rollself.role=role# Intermediate Class: Inherits the Base ClassclassIntermediate(Base):# Constructor to set agedef__init__(self,age,name,roll,role):super().__init__(name,roll,role)self.age=age# Derived Class: Inherits the Intermediate ClassclassDerived(Intermediate):# Method to Print Datadef__init__(self,age,name,roll,role):super().__init__(age,name,roll,role)defPrint_Data(self):print(f"TheNameis:{self.name}")print(f"TheAgeis:{self.age}")print(f"Theroleis:{self.role}")print(f"TheRollis:{self.roll}")# Creating Object of Base Classobj=Derived(21,"LokeshSingh",25,"SoftwareTrainer")# Printing the data with the help of derived classobj.Print_Data()
OutputThe Name is : Lokesh SinghThe Age is : 21The role is : Software TrainerThe Roll is : 25
Example 2: Multilevel Inheritance with Method Overriding
In this method, we have three different class and we have a method in the Intermediate class which we are going to Override in the derived class with the help ofMultilevel Inheritance.
Python3classShape:defarea(self):raiseNotImplementedError("SubclassesmustImplementarea()")classRectangle(Shape):def__init__(self,length,width):self.width=widthself.length=lengthdefarea(self):print(f"TheAreaofRectangleis{self.length*self.width}")classSquare(Rectangle):def__init__(self,side):super().__init__(side,side)defarea(self):print(f"TheAreaofRectangleis{self.length**2}")# Creating Objects of classRect=Rectangle(3,4)my_sqre=Square(4)Rect.area()my_sqre.area()
OutputThe Area of Rectangle is 12The Area of Rectangle is 16