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.
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.
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: 25In 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.
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.
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 EngineerIn 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.
Which of the following lines calls the `__init__` method of `BaseClass1` in the `DerivedClass` example?