In this Python lesson we want to learn about Python Hierarchical Inheritance, in python object oriented programming When more than one derived classes are created from a single base class that is called hierarchical inheritance.
Now let’s take a look at this image.
If you see in the image, we have four classes, Class A is our base or parent class, we have another three classes and all of them are extending from just one base class, as i have already said When more than one derived classes are created from a single base class that is called hierarchical inheritance. now there is a relationship between Class A and three derived classes(B, C, D), but there is no relationship between the derived classes, it means that we have a relationship between base class and derived classes, but there is no relationship between derived classes, for example we don’t have any relationship between Class B, Class C and Class D.
Now let’s create practical example in Python Hierarchical Inheritance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Animal: def run(self, name): self.name = name print(f'{self.name} Is Runing') class Dog(Animal): pass class Cat(Animal): pass dog = Dog() dog.run("Dog") cat = Cat() cat.run("Cat") |
In the example we have three python classes, class Animal is our base class and we have two more classes that are inheriting from just one base class. we have relationship between Class Animal and Class Cat, also between Class Animal and Class Dog, but there is no relationship between Class Cat and Class Dog.
Run the code and this is the result.