我目前正在学习python考试,但我还不了解Python 3中的MRO和线性化。
class F: pass
class G: pass
class H: pass
class E(G,H): pass
class D(E,F): pass
class C(E,G): pass
class B(C,H): pass
class A(D,B,E): pass
例如,在一个赋值中,有一个问题,在A类的线性化中,E是否有可能出现在C之前。
如何确定是否可行?如何尽可能简单地描述线性化算法(C3)?我非常感谢这方面的各种解释和资源,因为我很难理解 Python 中的线性化。
提前非常感谢!
Python 按 DFS 顺序查找父类或子类 不在 BFS 中
# This order is called Method Resolution Order (`mro()`)
class A(object):
def dothis(self):
print('Doing this in A')
class B(A):
pass
class C(object):
def dothis(self):
print('Doing this in C')
class D(B, C):
pass
d_instance = D()
d_instance.dothis()
# METHOD RESOLUTION ORDER
print(D.mro())
'''
OUTPUT:
# Doing this in A
# [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.A'>, <class '__main__.C'>, <class 'object'>]
A
| C
B(A) /
D(B, C)
RESOLUTION ORDER IS (DFS) = D-B-A-C
A
/
B(A) C(A)
/
D(B, C)
If the same class appears in mro, the earlier occurrences get removed
D-B-A-C-A -> D-B-C-A, hence still a DFS
RESOLUTION ORDER IS (In Diamond shape) = D-B-C-A
'''
类
E 继承自 G 和 H。
类 G 和 H 依赖(它们不从任何人继承)。
因为 E 类不依赖于类 C,所以可以在他之前初始化