gpt4 book ai didi

Python多重继承和MRO

转载 作者:行者123 更新时间:2023-12-01 03:21:58 24 4
gpt4 key购买 nike

我目前正在准备 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


'''

关于Python多重继承和MRO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41825723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com