Multilevel inheritance in Python involves deriving a class from another class, which in turn is derived from yet another class.
This creates a chain of inheritance, allowing the subclass to inherit properties and methods not only from its immediate parent class but also from the parent class’s ancestors, forming a hierarchical relationship.
This enables a hierarchical organization of classes and promotes code reusability.
Let’s illustrate multilevel inheritance with an example:
# Base class (also known as the parent class)
class Animal:
def __init__(self, species):
self.species = species
def make_sound(self):
pass
# Intermediate class (child of Animal)
class Mammal(Animal):
def __init__(self, species, sound):
super().__init__(species)
self.sound = sound
def make_sound(self):
return f"{self.species} makes {self.sound} sound."
# Derived class (child of Mammal)
class Dog(Mammal):
def __init__(self, breed, sound):
super().__init__("Dog", sound)
self.breed = breed
def make_sound(self):
return f"{self.breed} dog says {self.sound}."
# Create an instance of the Dog class and demonstrate multilevel inheritance
my_dog = Dog("Golden Retriever", "Woof")
print(my_dog.make_sound()) # Output: "Golden Retriever dog says Woof."
Code language: Python (python)
In this example, we have three classes: Animal
, Mammal
, and Dog
. The Animal
class is the base class that provides a basic structure for all animals.
The Mammal
class is derived from Animal
and adds additional attributes and a method.
Finally, the Dog
class is derived from Mammal
, inheriting attributes from both Mammal
and Animal
. The make_sound()
method is overridden at each level to provide specific behavior for each class.
As a result, when we create an instance of the Dog
class and call the make_sound()
method, it will display the message with the breed of the dog and the sound it makes, showcasing the multilevel inheritance in action.
Read More;
- How to use for loop in JSON Python?
- What is lambda function in Python for example?
- What is the dash function in Python?
- How to test a class with unittest Python?
- What is an example of a runtime error?
- How to run Python script from GitLab?
- What is an example of a string in Python?
- What is RegEx in Python with example?
- What is an example of a Boolean in Python?
- What is an example of built-in and user-defined functions in Python?
- What is an example of a constructor in Python?
- What is a dictionary in Python example?