Method Resolution Order
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 21 of 64.
Method Resolution Order (MRO) is the sequence Python uses to look for methods when multiple classes have the same method name.
Here is an example with multiple classes having the same method:
class A:
def method(self):
return "Method from A"
class B:
def method(self):
return "Method from B"
class C(A, B):
passCheck the MRO using __mro__:
print(C.__mro__)Output:
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)The __mro__ attribute is a tuple that contains all classes in the resolution order. The first element (__mro__[0]) is always the class itself (C), followed by parent classes from left to right (A, then B), and finally the built-in object class.
Create an object and call the method:
c = C()
print(c.method())Output:
Method from APython found the method in class A first (at index 1 in the MRO), so it used that one.
Change the inheritance order to see the difference:
class D(B, A): # B comes before A now
pass
print(D.__mro__)
d = D()
print(d.method())Output:
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
Method from BNow Python finds B's method first because B comes before A in the inheritance list. You can access specific classes in the MRO using indexing - D.__mro__[0] is D itself, D.__mro__[1] is B, and D.__mro__[2] is A.
You can also use the mro() method:
print(C.mro())This gives the same result as __mro__ but as a list.
Key Point: Python searches for methods in MRO order - the class itself first (index 0), then parent classes from left to right as listed in the class definition (indices 1, 2, etc.). The first method found gets used.
Challenge
MediumIn this challenge, you'll implement a class hierarchy.
You'll need to edit these files:
device.py: Implement the baseDeviceclassscreen.py: ImplementScreenclass that inherits fromDevicecomputer.py: ImplementComputerclass that inherits fromDevicelaptop.py: ImplementLaptopclass with multiple inheritancedriver.py- Implement test cases that will verify your implementation works correctly
Each file contains detailed TODO comments that will guide you step-by-step through the implementation.
Cheat sheet
Method Resolution Order (MRO) is the sequence Python uses to look for methods when multiple classes have the same method name.
Check MRO using __mro__ or mro():
class A:
def method(self):
return "Method from A"
class B:
def method(self):
return "Method from B"
class C(A, B):
pass
print(C.__mro__)
print(C.mro()) # Same result as a listPython searches for methods in MRO order - the class itself first, then parent classes from left to right as listed in the class definition:
c = C()
print(c.method()) # "Method from A" - A comes before B
class D(B, A): # B comes before A now
pass
d = D()
print(d.method()) # "Method from B" - B comes before ATry it yourself
# TODO: Import all required classes
# from device import Device
# from screen import Screen
# from computer import Computer
# from laptop import Laptop
def explain_mro(class_name):
# TODO: Print the MRO (Method Resolution Order) for the given class
# TODO: Format: "MRO for [class name]:" (note: NO space after the colon)
# TODO: Use class_name.__name__ to get the name of the class
# TODO: Use class_name.__mro__ to get the MRO tuple
# TODO: Print each class name in the MRO on separate lines
# TODO: Create an instance of the class
# TODO: Call power_on() on the instance and store the result
# TODO: Print: "Power on result: [result]"
# TODO: Print an empty line for better readability
pass
# Test your code
# TODO: Call explain_mro() with each class: Device, Screen, Computer, and Laptop
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes