When an instance receives a method call or attribute lookup, Python searches classes in a defined sequence. This method resolution order (MRO) selects the first matching implementation in an inheritance hierarchy. section 8.5.3
For a subclass with one superclass, Python checks the subclass first, then its superclass, then object. A missing method or attribute produces AttributeError after the searchable classes are exhausted. section 8.5.3
Use the MRO to understand common inheritance patterns:
- Override a method by defining the same method in the subclass; Python calls the subclass implementation for that instance. section 8.5.3
- Preserve superclass behavior with super(), then add subclass-specific actions. section 8.5.3
- Inspect a class's search sequence with its mro() method. section 8.5.3
- Treat attribute lookup as related but broader: instance attributes are checked first, while __getattr__ can provide a fallback when an attribute is absent. section 9.4.2
Overriding and extending a superclass method
class Supervisor(Employee): def login(self): print(f"A supervisor {self.name} just logged in.") def logout(self): super().logout() print("Additional logout actions for a supervisor") supervisor = Supervisor("John", "1001") supervisor.login() supervisor.logout() # A supervisor John just logged in. # An employee John just logged out. # Additional logout actions for a supervisor Supervisor.mro() # [<class '__main__.Supervisor'>, <class '__main__.Employee'>, <class 'object'>] section 8.5.3
Figure 8.10 MRO in a hierarchical class structure. When you call a method on an instance, Python checks the method with its class first. If the method is resolved, apply the implementation. If not, move up to its superclass. If it’s still not, move up to the object superclass, trying to resolve the method. If the method is still not resolved, raise the AttributeError exception. If there are more levels for the class inheritance structure, every level is checked.
Follow the lookup path from the instance's class through its superclasses and finally object, stopping at the first resolved implementation. section 8.5.3
