1

I am having a bit trouble understanding python's mro(Method resolution order). Python operates from left to right. So as per my understanding the order of calling for M should be. M, B, A, Z, X, Y

class X: pass
class Y: pass
class Z: pass

class A(X,Y): pass
class B(Y,Z): pass

class M(B,A,Z): pass

print(M.mro())

But the correct order of calling is.

    [<class '__main__.M'>,
 <class '__main__.B'>,
 <class '__main__.A'>,
 <class '__main__.X'>,
 <class '__main__.Y'>,
 <class '__main__.Z'>,
 <class 'object'>]

Can anyone explain the ordering and help me understand this. Thank you

1

1 Answer 1

2

mro has been based on C3 algorithm since Python2.3, and 'merge' is core of that algorithm. how merge works. According to your code, here we can list how to get mro(M):

mro(M) = [M] + merge(mro(B), mro(A), mro(Z), [B,A,Z])    

mro(B) = [B] + merge(mro(Y) , mro(Z)) = [B] + merge([Y] , [Z])
       = [B,Y] + merge([Z]) 
       = [B,Y,Z]

mro(A) = [A] + merge(mro(X) , mro(Y)) 
       = [A] + merge([X],[Y]) 
       = [A,X,Y]

mro(Z) = [Z]

Back to mro(M):

mro(M) = [M] + merge([B,Y,Z), [A,X,Y], [Z], [B,A,Z]) 
       = [M,B] + merge([Y,Z], [A,X,Y], [Z], [A,Z]) 
       = [M,B,A] + merge([Y,Z], [X,Y], [Z], [Z]) 
       = [M,B,A,X] + merge([Y,Z] + [Y] + [Z], [Z]) 
       = [M,B,A,X,Y] + merge([Z] + [Z] + [Z]) 
       = [M,B,A,X,Y,Z]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.