I am little confused about python multiple inheritance.
For example if you had:
class A(object):
def __init__(self):
print "init A"
super(A, self).__init__()
class B(A):
def __init__(self):
print "init B"
super(B, self).__init__()
class C(A):
def __init__(self):
print "init C"
super(C, self).__init__()
class D(C, B):
def __init__(self):
print "init D"
super(D, self).__init__()
if __name__ == '__main__':
D()
The method resolution order (MRO) would be D-C-B-A.
Why the order is not D-C-A-B-A?
解决方案
Python docs:
With new-style classes, dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where at least one of the parent classes can be accessed through multiple paths from the bottommost class). For example, all new-style classes inherit from object, so any case of multiple inheritance provides more than one path to reach object. To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic (meaning that a class can be subclassed without affecting the precedence order of its parents). Taken together, these properties make it possible to design reliable and extensible classes with multiple inheritance. For more detail, see https://www.python.org/download/releases/2.3/mro/.