Understand Method Resolution Order (MRO)
In this step, you will learn about Method Resolution Order (MRO) in Python. MRO is the order in which Python searches for a method in a class hierarchy. It is particularly important when dealing with multiple inheritance.
Let's create a new set of classes to illustrate MRO. Create a file named animal.py
in your ~/project
directory using the VS Code editor:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Generic animal sound"
class Mammal(Animal):
def speak(self):
return "Generic mammal sound"
class Dog(Mammal):
def speak(self):
return "Woof!"
class Cat(Mammal):
def speak(self):
return "Meow!"
Save the animal.py
file.
Now, let's create a new file named mro_example.py
in the ~/project
directory to demonstrate MRO:
from animal import Animal, Mammal, Dog, Cat
my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")
print(my_dog.speak())
print(my_cat.speak())
Save the mro_example.py
file.
In this example:
Animal
is the base class with a speak
method.
Mammal
inherits from Animal
and overrides the speak
method.
Dog
inherits from Mammal
and overrides the speak
method.
Cat
inherits from Mammal
and overrides the speak
method.
When you call my_dog.speak()
, Python first looks for the speak
method in the Dog
class. If it doesn't find it there, it looks in the Mammal
class, and then in the Animal
class. This order is determined by the MRO.
To run the mro_example.py
script, open your terminal and navigate to the ~/project
directory:
cd ~/project
Then, execute the script using the python
command:
python mro_example.py
You should see the following output:
Woof!
Meow!
Now, let's explore a more complex example with multiple inheritance. Create a new file named mro_complex.py
in the ~/project
directory:
class A:
def method(self):
return "A"
class B(A):
def method(self):
return "B"
class C(A):
def method(self):
return "C"
class D(B, C):
pass
d = D()
print(d.method())
print(D.mro())
Save the mro_complex.py
file.
In this example:
- Class
D
inherits from both B
and C
.
- Both
B
and C
inherit from A
.
- The
method
is defined in all three classes A
, B
, and C
.
To run the mro_complex.py
script, open your terminal and navigate to the ~/project
directory:
cd ~/project
Then, execute the script using the python
command:
python mro_complex.py
You should see the following output:
B
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
The output B
indicates that the method
from class B
is called. The D.mro()
method returns a tuple representing the method resolution order for class D
. In this case, the MRO is D -> B -> C -> A -> object
. This means that when you call d.method()
, Python first looks for the method in class D
, then in class B
, then in class C
, then in class A
, and finally in the base class object
.
Understanding MRO is essential for predicting the behavior of your code when using inheritance, especially multiple inheritance.