Beginner Level
Intermediate Level
Advanced Level
Introduction
One of the most widely used inheritance models in Python is hybrid inheritance. With hybrid inheritance, developers can combine multiple inheritance models like single, multiple, and multilevel inheritance to form complex class hierarchies that satisfy specific programming requirements. This tutorial aims to demystify hybrid inheritance in Python by exploring its syntax, implementation, and real-world applications. Whether you're new to Python or looking to deepen your understanding of inheritance in Python, this tutorial is an excellent place to start.
Table of Contents :
- What is Hybrid inheritance?
- Creating Subclasses with Hybrid Inheritance
- Method Resolution Order (MRO)
What is Hybrid inheritance?
- Hybrid inheritance is a combination of two or more types of inheritance (single, multiple, and multilevel inheritance).
- It is a way of creating a hierarchy of classes with complex inheritance relationships.
- In Python, we achieve hybrid inheritance using the `class` keyword and defining classes with different types of inheritance relationships.
Creating Subclasses with Hybrid Inheritance :
- To create subclasses with hybrid inheritance, we define classes with different types of inheritance relationships.
- 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")
class Bulldog(Dog):
def speak(self):
super().speak()
print("This Bulldog growls")
class Persian(Cat):
def speak(self):
super().speak()
print("This Persian purrs")
class Pug(Bulldog, Persian):
def __init__(self, name):
super().__init__(name, "Pug")
def speak(self):
super().speak()
print("This Pug snorts")
p = Pug("Puggy")
p.speak()
# Output: This dog barks \n This cat meows \n This Bulldog growls \n This Persian purrs \n This Pug snorts
Method Resolution Order (MRO) :
- In hybrid inheritance, Python determines the order in which the methods of the superclasses are called using MRO algorithm.
- The MRO algorithm follows a combination of the C3 linearization and 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 A:
def speak(self):
print("This is A speaking")
class B(A):
def speak(self):
print("This is B speaking")
class C(A):
def speak(self):
print("This is C speaking")
class D(B, C):
pass
print(D.mro())
# Output: [, , , , ]
Prev. Tutorial : Hierarchical inheritance
Next Tutorial : Super() function