That’s because of Python’s method resolution order. You can view the MRO of your classes by calling Class4.mro() for example. You will see that Class3 comes before Class1. This is because Python’s MRO (https://www.python.org/download/releases/2.3/mro/) uses the C3 Linearization algorithm (https://en.wikipedia.org/wiki/C3_linearization).

Quoting Guido van Rossum (from wikipedia):

Basically, the idea behind C3 is that if you write down all of the ordering rules imposed by inheritance relationships in a complex class hierarchy, the algorithm will determine a monotonic ordering of the classes that satisfies all of them. If such an ordering can not be determined, the algorithm will fail.

You can read into the algorithm, but a simplistic view I like to hold about the alogirthm is this: It’s basically a DFS from left to right, but a subclass will always be earlier than it’s superclass.

Note: this is a simplistic view of the rule, and it not covers the algorithm nor the failed cases, but in most cases it’s a good way to remember the MRO basics.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top