concept method resolution order in category python

appears as: method resolution order, method resolution order
Practices of the Python Pro

This is an excerpt from Manning's book Practices of the Python Pro.

  • Method resolution order is key to keeping multiple inheritance straight.
  • Because Liger inherits both from Lion and Tiger, you might have expected it would eat the same prey they eat, at a minimum. super() works a bit differently under multiple inheritance. When super().eats() is called, Python starts searching for the definition of eats() that it should use. Python does this through a process called method resolution order, which determines the list of classes Python will search, in order.

    These are the steps for method resolution order:

    Figure 8.7. How Python determines the method resolution order for a class

    When you ask for super().eats(), Python will work its way through the method resolution order until it finds an eats() method on one of the classes (other than the one you called super() from). As you can see, it finds Lion first, which returns ['wildebeest']. Liger then adds its own list of prey animals, resulting in the list you saw in the output.

    Inspecting the method resolution order

    You can see the method resolution order for any class by using its __mro__ attribute:

    >>> Liger.__mro__
    (<class '__main__.Liger'>, <class '__main__.Lion'>,
     <class '__main__.Tiger'>, <class '__main__.BigCat'>, <class 'object'>)

    You can make multiple inheritance work as you expected by practicing cooperative multiple inheritance. In cooperative multiple inheritance, each class commits to having the same method signatures (substitutability) and to calling super().some_method() from within its own some_method(). The presence of super() in each method means Python will keep going through the method resolution order even after it finds a method. This ensures that no class blocks execution or breaks things with an unexpected interface. The classes play nicely together.