In this lesson, you will learn how to inspect and predict the specific path Python follows when searching for methods across a class hierarchy.
The Search Order
When you call a method on an object, Python must find the corresponding code. If the method exists in the object's class, it uses that. But if you are using inheritance—especially multiple inheritance—Python needs a consistent "game plan" to decide which parent class to check first, second, or last. This sequence is known as the Method Resolution Order (MRO).
Python uses a specific algorithm called C3 Linearization to ensure that the search order is predictable and respects the hierarchy you defined.
Inspecting the MRO
You don’t have to guess the order; Python provides a built-in attribute called __mro__ on every class. This returns a tuple showing the exact search path.
Consider this hierarchy:
class Animal:
pass
class Dog(Animal):
pass
# We can check the search order for Dog
print(Dog.__mro__)
When you run this, you will see output like:
(<class '__main__.Dog'>, <class '__main__.Animal'>, <class 'object'>)
Why it Matters
The MRO tells you exactly who "wins" if two parent classes happen to have methods with the same name. If you have a class Robot that inherits from Machine and ElectronicDevice, Python will check Robot first, then the first class listed in the parentheses, then the second, and finally the base object class.
If you ever find that a method is behaving unexpectedly—perhaps you thought Machine.run() would execute, but ElectronicDevice.run() was called instead—printing the class’s __mro__ attribute will immediately reveal why Python skipped the one you expected. It is the definitive map of your object’s ancestry and the final authority on method lookup.
Key Takeaway: The __mro__ attribute provides a tuple representing the exact linear order in which Python searches for methods, ensuring consistency even in complex multiple inheritance scenarios.