Why is this an ambiguous MRO?

后端 未结 2 1922
遥遥无期
遥遥无期 2020-12-06 16:35
class First(object):
    def __init__(self):
        print("first")

class Second(First):
    def __init__(self):
        print("second")

class          


        
相关标签:
2条回答
  • 2020-12-06 16:54

    If we apply the C3 linearization algorithm:

    i) take the head of the first list.

    ii) if this head is not in the tail of any of the other lists, then add it to the linearization of C and remove it from the lists in the merge

    iii) otherwise look at the head of the next list and take it if it is a good head

    iv) Then repeat the operation until all the class is removed or it is impossible to find good heads.

    O : is the object class

    L[First] = First O

    L[Second] = Second + merge(L[First], First)

    Now solving L[Second]

    L[Second] = Second + merge(FirstO, First)

    First is the head in list FirstO and in the list First, so it is a good head.

    L[Second] = Second + First + merge(O)

    O is the only head in the list and it is good head

    L[Second] = Second + First + O

    L[Second] = Second First O

    L[Third] = Third + merge(L[First], L[Second], FirstSecond)

    Now solving L[Third]

    L[Third] = Third + merge(FirstO, SecondFirstO, FirstSecond)

    L[Third] = Third + impossible to find good heads.

    First is the head in the list FirstO but it is the tail in the list SecondFirstO, Second is the head in the list SecondFirstO but it is the tail in the list FirstSecond and O is tail in both the list FirstO, SecondFirstO so it is not possible to find good heads.

    0 讨论(0)
  • 2020-12-06 16:57

    To be "consistent" the MRO should satisfy these constraints:

    1. If a class inherits from multiple superclasses, the ones it lists earlier in the superclass list should come earlier in the MRO than the ones it lists later.
    2. Every class in the MRO should come before any of its superclasses.

    Your proposed hierarchy does not have any possible ordering meeting these constraints. Because Third is defined to inherit from First before Second, First should come before Second in the MRO. But because Second inherits from First, Second should come before First in the MRO. This contradiction cannot be reconciled.

    You can read more about the precise method Python uses to compute the MRO, which is called the C3 linearization algorithm.

    0 讨论(0)
提交回复
热议问题