gpt4 book ai didi

python - 在 python 中揭开 super 的神秘面纱?

转载 作者:太空狗 更新时间:2023-10-30 02:04:05 26 4
gpt4 key购买 nike

我试图了解 super 在 python 中的工作原理并尝试了以下示例:

class A(object):
def __init__(self):
print "in A's init"

class B(object):
def __init__(self):
print "in B's init"

class C(A,B):
def __init__(self):
super(C,self).__init__()
print "In C"

if __name__=="__main__":
c=C()

相当简单..我尝试了以下 super 调用(在此处显示结果):

>>> super(B,c).__init__()
>>> super(B,c).__init__()
>>> super(A,c).__init__()
in B's init
>>> super(A,c).__init__()
in B's init
>>> super(A,c).__init__()
in B's init
>>> super(B,c).__init__()
>>> super(C,c).__init__()
in A's init

我不明白为什么 super(A,c).__init__() 打印出它在 B 的初始化中?

最佳答案

Python 的 super() 应该被称为“next-in-mro”,因为它不一定向上调用父级;相反,它可以调用 sibling 。

检查类结构的方法解析顺序很容易:

 >>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)

你可以看到 BA 之后的下一个类。

这种设计的原因是它让 super 调用链访问链中的每个类不超过一次。它支持一种称为“合作多重继承”的编程风格,这种风格有时非常有用。

这里有一些引用资料,包括指向 Dylan 的 next-method 的链接,该方法用作 Python 的 super() 的模型:

关于python - 在 python 中揭开 super 的神秘面纱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564908/

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