Python Multiple Inheritance
Explanation with Examples



In Python, a class can inherit from more than one parent class. This is called Multiple Inheritance.

Don't worry if this sounds confusing. Let's break it down with very simple examples.

What is Inheritance?

Inheritance means one class (called the child) can use code from another class (called the parent).

With multiple inheritance, a child class can use code from two or more parent classes.

Simple Example of Multiple Inheritance

# First Parent Class
class Father:
    def skills(self):
        print("Father: Cooking, Driving")

# Second Parent Class
class Mother:
    def hobbies(self):
        print("Mother: Painting, Gardening")

# Child class inherits from both Father and Mother
class Child(Father, Mother):
    pass

# Create an object of Child
c = Child()
c.skills()
c.hobbies()
    
Father: Cooking, Driving
Mother: Painting, Gardening

Explanation:

What If Both Parents Have the Same Function Name?

This is where it gets interesting. Python follows something called MRO (Method Resolution Order).

Let's see an example:

class Father:
    def talk(self):
        print("Father: I talk about sports.")

class Mother:
    def talk(self):
        print("Mother: I talk about arts.")

class Child(Father, Mother):
    pass

c = Child()
c.talk()
    
Father: I talk about sports.

Explanation:

How to Check MRO (Method Resolution Order)?

You can check which class Python will look at first using this:

print(Child.__mro__)
(<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class 'object'>)

Explanation:

This tells you the order in which Python will check for methods:

  1. First it looks in Child.
  2. If not found, it looks in Father.
  3. Then in Mother.
  4. And finally in object, which is the default base class in Python.

Conclusion

Multiple inheritance lets a class use features from more than one parent. Just remember:

With this knowledge, you’re now ready to understand more about Python classes and how powerful they can be!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M