Introduction

Hierarchical inheritance is a type of inheritance in which multiple classes inherit properties and methods from the same parent class. This allows for a hierarchy or tree-like structure of classes, with the parent class at the top and child classes branching out from it. In Python, implementing hierarchical inheritance is easy and can lead to more efficient and organized code. In this tutorial, we'll explore how to create and use hierarchical inheritance in Python, along with some practical examples to help reinforce your understanding.

Table of Contents :

  • What is Hierarchical inheritance
  • Creating Subclasses with Hierarchical Inheritance
  • Method Resolution Order (MRO)

What is Hierarchical inheritance :

  • Hierarchical inheritance is a type of inheritance where multiple subclasses are derived from a single superclass.
  • It is a way of creating a hierarchy of classes in which each subclass inherits properties and methods from a common superclass.
  • In Python, we achieve hierarchical inheritance using the `class` keyword and defining each subclass with the same superclass.

Creating Subclasses with Hierarchical Inheritance :

  • To create subclasses with hierarchical inheritance, we define a superclass and then define each subclass with that same superclass.
  • Example:

class Animal:
   def __init__(self, species):
       self.species = species
   def speak(self):
       print("This animal speaks")

class Dog(Animal):
   def __init__(self, name, breed):
       self.name = name
       self.breed = breed
       super().__init__("Dog")
   def speak(self):
       print("This dog barks")

class Cat(Animal):
   def __init__(self, name, breed):
       self.name = name
       self.breed = breed
       super().__init__("Cat")
   def speak(self):
       print("This cat meows")

d = Dog("Buddy", "Bulldog")
d.speak()           

# Output: This dog barks

c = Cat("Kitty", "Persian")
c.speak()           

# Output: This cat meows


Method Resolution Order (MRO):

  • In hierarchical inheritance, Python determines the order in which the methods of the superclasses are called using MRO algorithm.
  • The MRO algorithm follows a Depth First Search (DFS) approach to traverse the hierarchy of classes.
  • We can view the MRO for a class using the `mro()` method.
  • Example:

class Animal:
   def speak(self):
       print("This animal speaks")

class Dog(Animal):
   def speak(self):
       print("This dog barks")

class Cat(Animal):
   def speak(self):
       print("This cat meows")

class Bulldog(Dog):
   def speak(self):
       super().speak()
       print("This Bulldog growls")

class Persian(Cat):
   def speak(self):
       super().speak()
       print("This Persian purrs")

b = Bulldog()
b.speak()          
# Output: This dog barks \n This Bulldog growls

p = Persian()
p.speak()           
# Output: This cat meows \n This Persian purrs