Method Resolution Order (MRO)

Some people don't like multiple inheritance because of the constraints it has in other programming languages, for instance, the so-called diamond problem. When a class extends from two or more, and all of those classes also extend from other base classes, the bottom ones will have multiple ways to resolve the methods coming from the top-level classes. The question is, which of these implementations is used?

Consider the following diagram, which has a structure with multiple inheritance. The top-level class has a class attribute and implements the __str__ method. Think of any of the concrete classes, for example, ConcreteModuleA12—it extends from BaseModule1 and BaseModule2, and each one of them will take the implementation of __str__ from BaseModule. Which of these two methods is going to be the one for ConcreteModuleA12?

 

With the value of the class attribute, this will become evident:

class BaseModule:
module_name = "top"

def __init__(self, module_name):
self.name = module_name

def __str__(self):
return f"{self.module_name}:{self.name}"


class BaseModule1(BaseModule):
module_name = "module-1"


class BaseModule2(BaseModule):
module_name = "module-2"


class BaseModule3(BaseModule):
module_name = "module-3"


class ConcreteModuleA12(BaseModule1, BaseModule2):
"""Extend 1 & 2"""


class ConcreteModuleB23(BaseModule2, BaseModule3):
"""Extend 2 & 3"""

Now, let's test this to see what method is being called:

>>> str(ConcreteModuleA12("test"))
'module-1:test'

There is no collision. Python resolves this by using an algorithm called C3 linearization or MRO, which defines a deterministic way in which methods are going to be called.

In fact, we can specifically ask the class for its resolution order:

>>> [cls.__name__ for cls in ConcreteModuleA12.mro()]
['ConcreteModuleA12', 'BaseModule1', 'BaseModule2', 'BaseModule', 'object']

Knowing about how the method is going to be resolved in a hierarchy can be used to our advantage when designing classes because we can make use of mixins.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.11.19