Python MRO Explained: Method Resolution Order

Two parent classes. Same method name. One child class. Which one does Python call? I assumed Python would just crash — or at least throw an error. It didn't. It silently picked one. And I had no idea which one or why. ━━━━━━━━━━━━━━━━━━━━━━ This is Multiple Inheritance in Python. class A: ····def hello(self): print("Hello from A") class B: ····def hello(self): print("Hello from B") class C(A, B): ····pass C().hello() ━━━━━━━━━━━━━━━━━━━━━━ Output: Hello from A But why A and not B? Python follows something called MRO — Method Resolution Order. It uses an algorithm called C3 Linearization. The rule is simple: Python reads left to right in the inheritance list, then goes up. C → A → B → object So it finds hello() in A first — and stops there. ━━━━━━━━━━━━━━━━━━━━━━ You can actually see Python's MRO yourself: print(C.mro) Output: ▶ C → A → B → object ━━━━━━━━━━━━━━━━━━━━━━ My Software Engineering brain connected this immediately. In Java, multiple inheritance isn't even allowed for classes — exactly because of this ambiguity. Java forces you to use interfaces instead. Python allows it — but quietly follows a strict order behind the scenes. The lesson: Python is never random. There's always a rule. You just have to find it. ━━━━━━━━━━━━━━━━━━━━━━ Senior developers — has MRO ever caused a bug in your production code that took you a while to trace? Genuinely curious how often this actually bites people. #Python #OOP #DataScience #SoftwareEngineering

  • diagram

To view or add a comment, sign in

Explore content categories