Hybrid inheritance is a combination of two or more types of inheritance in a single program. It allows for more complex class hierarchies and greater flexibility in design by mixing different inheritance patterns such as single, multiple, multilevel, and hierarchical inheritance.
Hybrid inheritance is useful for:
Let’s explore a practical example to understand hybrid inheritance better.
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
class Mammal(Animal):
def walk(self):
print(f"{self.name} is walking")
class Bird(Animal):
def fly(self):
print(f"{self.name} is flying")
class Bat(Mammal, Bird):
def __init__(self, name):
super().__init__(name)
def hang(self):
print(f"{self.name} is hanging upside down")
class Dog(Mammal):
def bark(self):
print(f"{self.name} says Woof!")
if __name__ == "__main__":
bat = Bat("Bruce")
dog = Dog("Buddy")
# Using methods from the base and intermediate classes
bat.eat() # Output: Bruce is eating
bat.walk() # Output: Bruce is walking
bat.fly() # Output: Bruce is flying
bat.hang() # Output: Bruce is hanging upside down
dog.eat() # Output: Buddy is eating
dog.walk() # Output: Buddy is walking
dog.bark() # Output: Buddy says Woof!
Animal:
__init__ method initializes the name attribute.Mammal:
name attribute and eat method from the Animal class.Bird:
name attribute and eat method from the Animal class.Bat (Multiple Inheritance):
Mammal and Bird.name attribute, eat method, walk method, and fly method.Bat.Dog:
Mammal.name attribute, eat method, and walk method.Dog.In hybrid inheritance, the MRO determines the order in which methods are inherited and called. Python uses the C3 linearization algorithm to compute the MRO, ensuring a consistent and predictable order.
print(Bat.mro())
# Output: [<class '__main__.Bat'>, <class '__main__.Mammal'>, <class '__main__.Bird'>, <class '__main__.Animal'>, <class 'object'>]