Multiple Inheritance is a feature in Object-Oriented Programming (OOP) where a child class inherits from more than one parent class.
In simple words:
One child class â Multiple parent classes
Why Use Multiple Inheritance?
- Combine features from multiple classes
- Promote code reuse
- Create flexible and modular designs
Basic Syntax
class Parent1:
passclass Parent2:
passclass Child(Parent1, Parent2):
pass
The child class can access methods and variables from both parent classes.
Simple Example
class Father:
def skill1(self):
print("Gardening")class Mother:
def skill2(self):
print("Cooking")class Child(Father, Mother):
def skill3(self):
print("Programming")c = Child()c.skill1()
c.skill2()
c.skill3()
Output:
Gardening
Cooking
Programming
Here:
Childinherits from bothFatherandMother- It can use methods from both classes
Constructor in Multiple Inheritance
If both parent classes have constructors:
class Father:
def __init__(self):
print("Father Constructor")class Mother:
def __init__(self):
print("Mother Constructor")class Child(Father, Mother):
def __init__(self):
super().__init__()c = Child()
Python follows something called MRO (Method Resolution Order).
Method Resolution Order (MRO)
MRO decides the order in which Python searches for methods in multiple inheritance.
You can check it using:
print(Child.__mro__)
Python searches from left to right in the inheritance list.
In this case:
Child â Father â Mother â object
Diamond Problem
The diamond problem occurs when:
- Two parent classes inherit from the same base class
- A child class inherits from both of them
Python solves this using MRO (C3 Linearization).
Example:
class A:
def show(self):
print("Class A")class B(A):
passclass C(A):
passclass D(B, C):
passd = D()
d.show()
Python ensures A is only called once.
Key Points
- A class can inherit from multiple classes
- Order of parents matters
- Python uses MRO to resolve conflicts
super()works with MRO
When to Use Multiple Inheritance
- When combining independent features
- When designing mixin classes
- When behavior needs to be shared from multiple sources
Key Takeaway
Multiple Inheritance allows a class to inherit from more than one parent class.
Python handles complexity using Method Resolution Order, making multiple inheritance powerful and manageable.