Python Multilevel Inheritance Tutorial 🎯

beginner
5 min

Python Multilevel Inheritance Tutorial 🎯

Welcome to the Python Multilevel Inheritance Tutorial! In this lesson, we'll dive into one of the most powerful features of Object-Oriented Programming (OOP) - Multilevel Inheritance. By the end of this tutorial, you'll be able to create sophisticated and well-structured Python programs using multiple levels of inheritance. 💡 Pro Tip: This tutorial is suitable for beginners and intermediate learners alike.

Understanding Inheritance 📝

Inheritance is a mechanism in OOP that allows one class to derive properties and methods from another class. This helps in code reusability, reducing redundancy, and creating a hierarchy of classes.

python
class BaseClass: def __init__(self, name): self.name = name def display(self): print(self.name) class DerivedClass(BaseClass): def __init__(self, name, age): super().__init__(name) # Calling the constructor of the BaseClass self.age = age def display_details(self): self.display() # Calling the display method from the BaseClass print(f'Age: {self.age}') # Creating an instance and calling the display_details method obj = DerivedClass('John', 25) obj.display_details() # Output: John # Age: 25

In the above example, DerivedClass inherits the name attribute and the display method from BaseClass. It also adds its own attribute age and method display_details.

Introducing Multilevel Inheritance 📝

Multilevel inheritance is a process where a class derives properties and methods from multiple parent classes. It can help in further code reusability and class hierarchies.

python
class BaseClass1: def __init__(self, name): self.name = name def display(self): print(self.name) class IntermediateClass(BaseClass1): def __init__(self, name, age): super().__init__(name) # Calling the constructor of the BaseClass1 self.age = age class DerivedClass(IntermediateClass): def __init__(self, name, age, job): super().__init__(name, age) # Calling the constructor of the IntermediateClass self.job = job def display_details(self): self.display() # Calling the display method from the BaseClass1 print(f'Age: {self.age}') print(f'Job: {self.job}') # Creating an instance and calling the display_details method obj = DerivedClass('John', 25, 'Software Engineer') obj.display_details() # Output: John # Age: 25 # Job: Software Engineer

In this example, DerivedClass inherits properties and methods from both BaseClass1 and IntermediateClass. It not only inherits the name attribute and the display method from BaseClass1 but also inherits the age attribute from IntermediateClass.

Quiz 💡

Quick Quiz
Question 1 of 1

Which of the following lines calls the `__init__` method of `BaseClass1` in the `DerivedClass` example?