Python hybrid inheritance with example

Share Your Love

In Python hybrid inheritance refers to a situation where a subclass inherits from multiple base classes, combining both single inheritance and multiple inheritance. This allows the subclass to inherit attributes and methods from multiple parent classes, creating a more complex inheritance hierarchy.

Here’s an example that demonstrates hybrid inheritance:

class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(f"{self.name} is eating.")


class Mammal(Animal):
    def give_birth(self):
        print(f"{self.name} is giving birth.")


class Bird(Animal):
    def fly(self):
        print(f"{self.name} is flying.")


class Bat(Mammal, Bird):
    def __init__(self, name):
        super().__init__(name)

    def echolocate(self):
        print(f"{self.name} is using echolocation.")


bat = Bat("Batty")

bat.eat()        # Output: Batty is eating.
bat.give_birth() # Output: Batty is giving birth.
bat.fly()        # Output: Batty is flying.
bat.echolocate() # Output: Batty is using echolocation.

In the example above, we have four classes: Animal, Mammal, Bird, and Bat. Animal is the base class that provides the common attributes and methods for all animals. Mammal and Bird are subclasses of Animal that add specific behaviors for mammals and birds, respectively.

The Bat class is a subclass of both Mammal and Bird, creating a hybrid inheritance. It inherits attributes and methods from both parent classes. By calling super().__init__(name) in the Bat class’s __init__ method, we ensure that the name an attribute is properly initialized from the Animal class.

The Bat class introduces its own method echolocate, which is specific to bats.

When we create an instance of Bat and invoke its methods, we can see that it can access and utilize methods from both the Mammal and Bird classes, as well as its own unique method.

Hybrid inheritance can be useful when you want to combine the characteristics of multiple base classes to create a more specialized subclass. However, it can also introduce complexities, such as the potential for method name clashes or difficulties in managing the inheritance hierarchy. It is important to carefully design and manage your class hierarchy when using hybrid inheritance.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter