我在理解python的mro(方法解析顺序)时遇到了一些麻烦。 Python从左到右运行。因此,据我了解,调用M的顺序应为。
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())
但是正确的调用顺序是。
[<class '__main__.M'>,
<class '__main__.B'>,
<class '__main__.A'>,
<class '__main__.X'>,
<class '__main__.Y'>,
<class '__main__.Z'>,
<class 'object'>]
任何人都可以解释订购信息并帮助我理解这一点。谢谢
最佳答案
自Python2.3起,mro就一直基于C3算法,而“合并”是该算法的核心。 how merge works。
根据您的代码,在这里我们可以列出如何获取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]
返回
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]