我试图了解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()
Run Code Online (Sandbox Code Playgroud)
相当简单..我尝试了以下超级调用(在此处显示结果):
>>> 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
Run Code Online (Sandbox Code Playgroud)
我不明白为什么super(A,c).__init__()在B的init 中打印出它?
Python的super()应该被称为"next-in-mro",因为它不一定向父母调用; 相反,它可以称为兄弟姐妹.
很容易检查类结构的方法解析顺序:
>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)
Run Code Online (Sandbox Code Playgroud)
你可以看到B是A之后的下一课.
这种设计的原因是它允许超级调用链访问链中的每个类不超过一次.这支持一种称为"协作多重继承"的编程风格,有时非常有用.
以下是一些参考资料,包括作为Python的super()模型的Dylan的next方法的链接:
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |