Are you exploring the object-oriented programming concept of Python and coming across the term hierarchical inheritance?
In Python, we have different types of inheritance, such as single, multiple, hybrid, multilevel, and hierarchical inheritance. The focus of this article is on hierarchical inheritance in Python. To learn about the different types of inheritance that can be implemented with Python, you can refer to our more comprehensive guide here.
We’ll discuss what it is, how it works, and a practical example or implementation, so let’s begin.
What is Hierarchical Inheritance in Python?
Hierarchical inheritance is a type in Python where you can inherit more than one class from the base or parent class. Let’s say you have a base class animal with some animal properties; you can inherit these properties from other animals like cats, dogs, and lions because these are also animals.
These properties can be any characteristics like eating, sleeping, and hunting. Each animal has these properties, so you can define them in the base class and inherit them from each animal. Let’s see a practical example:
# base class class Animal(): def animal(self): print("I'm an Animal") # child class 1 class Cat(Animal): def cat(self): print("I'm a cat Meow Meow!") # child class 2 class Dog(Animal): def dog(self): print("I'm a dog Brak Bark!") # create object of child classes cat = Cat() dog = Dog() print("Cat") cat.animal() cat.cat() print("\nDog") dog.animal() dog.dog()
Cat I'm an Animal I'm a cat Meow Meow! Dog I'm an Animal I'm a dog Brak Bark!
As you can see in the above example, we have a base class Animal which has a function, and the two child classes, Cat and Dog, are inheriting the Animal class, so they are authorized to access the properties of class Animal.
As we know, inheritance allows you to access the base/parent class members from the child class. Similarly, in the above example, we are accessing the animal() function using the objects of the child classes.
How does it work?
The term itself is self-explanatory; it works in a hierarchy, just like the hierarchy of employees of an organization. There is a top position like the CEO, then Managers and lower-level workers.
Using this is the best solution for such applications with a hierarchical structure.
To summarise the article on hierarchical inheritance in Python, we have discussed what a hierarchical structure is and how it works. In addition, we have discussed its operation, along with a practical example.
Here is a quick recap of the topics covered in this article.
- What is hierarchical inheritance in Python?
- How does it work in Python?
- What is a hierarchical structure?
Learning moment 💡, what is the best suitable scenario for this type of inheritance?