作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我试图了解 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'>)
你可以看到 B 是 A 之后的下一个类。
这种设计的原因是它让 super 调用链访问链中的每个类不超过一次。它支持一种称为“合作多重继承”的编程风格,这种风格有时非常有用。
这里有一些引用资料,包括指向 Dylan 的 next-method 的链接,该方法用作 Python 的 super() 的模型:
关于python - 在 python 中揭开 super 的神秘面纱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564908/
我是一名优秀的程序员,十分优秀!