Practice Multiple Inheritance
Python allows a class to inherit from more than one parent class. This is called multiple inheritance. It can be a powerful tool for mixing functionalities from different sources, but it also introduces complexity, particularly in how Python decides which parent's method to use if they have the same name.
This search order is called the Method Resolution Order (MRO). Python uses an algorithm called C3 linearization to determine a consistent and predictable MRO.
Let's explore this with a new example. Open the file multiple_inheritance.py from the file explorer and add the following code:
## File: multiple_inheritance.py
class ParentA:
def speak(self):
print("Speaking from ParentA")
def common_method(self):
print("ParentA's common method")
class ParentB:
def speak(self):
print("Speaking from ParentB")
def common_method(self):
print("ParentB's common method")
## Child inherits from A, then B
class Child_AB(ParentA, ParentB):
pass
## Child inherits from B, then A
class Child_BA(ParentB, ParentA):
def common_method(self):
print("Child_BA's own common method")
if __name__ == "__main__":
child1 = Child_AB()
child2 = Child_BA()
print("--- Investigating Child_AB (ParentA, ParentB) ---")
child1.speak()
child1.common_method()
## The .mro() method shows the Method Resolution Order
print("MRO for Child_AB:", [c.__name__ for c in Child_AB.mro()])
print("\n--- Investigating Child_BA (ParentB, ParentA) ---")
child2.speak()
child2.common_method()
print("MRO for Child_BA:", [c.__name__ for c in Child_BA.mro()])
Save the file. Here, Child_AB inherits from ParentA and then ParentB. Child_BA inherits in the reverse order. When a method is called, Python searches for it in the order specified by the MRO.
Run the script from the terminal:
python multiple_inheritance.py
You will see the following output:
--- Investigating Child_AB (ParentA, ParentB) ---
Speaking from ParentA
ParentA's common method
MRO for Child_AB: ['Child_AB', 'ParentA', 'ParentB', 'object']
--- Investigating Child_BA (ParentB, ParentA) ---
Speaking from ParentB
Child_BA's own common method
MRO for Child_BA: ['Child_BA', 'ParentB', 'ParentA', 'object']
From the output, you can observe:
child1.speak() calls the method from ParentA because ParentA comes first in Child_AB's MRO.
child2.speak() calls the method from ParentB because ParentB comes first in Child_BA's MRO.
child2.common_method() calls the version defined directly in Child_BA, as Python finds it there first before checking the parents.
Understanding the MRO is crucial for predicting behavior in multiple inheritance scenarios.