How does Python pass __init__ parameters with multiple inheritance

前端 未结 3 1636
余生分开走
余生分开走 2021-01-14 12:52

I have this code, showing a classic diamond pattern:

class A:
    def __init__( self, x ):
        print( \"A:\" + x )


class B( A ):
    def __init__( self         


        
3条回答
  •  星月不相逢
    2021-01-14 13:25

    Python uses the C3 linearization algorithm to establish the method resolution order, which is the same order that super delegates in.

    Basically, the algorithm keeps lists for every class containing that class and every class it inherits from, for all classes that the class in question inherits from. It then constructs an ordering of classes by taking classes that aren't inherited by any unexamined classes one by one, until it reaches the root, object. Below, I use O for object for brevity:

    L(O) = [O]
    
    L(A) = [A] + merge(L(O), [O]) = [A, O]
    
    L(B) = [B] + merge(L(A), [A]) = [B] + merge([A, O], [A]) = [B, A] + merge([O]) 
         = [B, A, O]
    
    L(C) = [C] + merge(L(A), [A]) = [C] + merge([A, O], [A]) = [C, A] + merge([O]) 
         = [C, A, O]
    
    L(D) = [D] + merge(L(B), L(C), [B, C]) = [D] + merge([B, A, O], [C, A, O], [B, C])
         = [D, B] + merge([A, O], [C, A, O], [C]) = [D, B, C] + merge([A, O], [A, O])
         = [D, B, C, A, O]
    

提交回复
热议问题