Multiple inheritance
Inheritance means one class can "borrow" or "inherit" attributes and methods from another class. For example:
-
A
Dog
class can inherit from an class and share its behaviors.Animal
What is multiple inheritance?
Multiple inheritance is when a class can inherit from more than one class. This lets your class combine features from different sources. For example:
class Animal:
def speak(self):
return "I make a sound"
class Pet:
def cuddle(self):
return "I like cuddles"
class Dog(Animal, Pet):
pass
dog = Dog()
print(dog.speak()) # Output: I make a sound
print(dog.cuddle()) # Output: I like cuddles
Here, Dog
inherits from both Animal
Pet
speak()
cuddle()
The diamond problem
When a class inherits from multiple classes that share a common parent, things can get tricky. Imagine this structure:
A
/ \
B C
\ /
D
A
is the top class.B
andC
inherit fromA
.D
inherits from bothB
andC
.
Now, if you call a method on D
, which version of the method does it use?
D
could inherit fromB
’s version orC
’s version, which might be different. This confusion is called the diamond problem.
Example of the diamond problem
class A:
def greet(self):
return "Hello from A"
class B(A):
def greet(self):
return "Hello from B"
class C(A):
def greet(self):
return "Hello from C"
class D(B, C):
pass
d = D()
print(d.greet()) # Output: Hello from B
Why does it choose B
’s version? This is where Method Resolution Order (MRO) comes in.
Method resolution order (MRO)
The MRO is the rule Python uses to decide which class’s method to call. It checks classes in a specific order:
- The child class first.
- The parent classes in the order they are listed.
- Avoids calling the same class multiple times.
You can check the MRO of a class using:
print(D.mro())
For the above example, it outputs:
[, , , , ]
Python follows this order to decide which method to use.
Why does Python handle MRO Well?
Python uses a method called the C3 Linearization Algorithm to:
- Make MRO predictable.
- Avoid repeatedly calling methods from the same class.
Key points to remember:
-
Multiple Inheritance lets you combine features from multiple classes.
- The Diamond Problem occurs when a class inherits from multiple classes with a common parent.
- MRO decides the order in which methods are called to avoid confusion.