在 python 中揭开 super 的神秘面纱? [英] demystify super in python?

查看:12
本文介绍了在 python 中揭开 super 的神秘面纱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A 类(对象):def __init__(self):打印在 A 的初始化中"B类(对象):def __init__(self):打印在 B 的初始化中"C(A,B)类:def __init__(self):super(C,self).__init__()打印在 C"如果 __name__=="__main__":c=C()

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

<预><代码>>>>super(B,c).__init__()>>>super(B,c).__init__()>>>super(A,c).__init__()在 B 的初始化中>>>super(A,c).__init__()在 B 的初始化中>>>super(A,c).__init__()在 B 的初始化中>>>super(B,c).__init__()>>>super(C,c).__init__()在 A 的 init 中

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

解决方案

Python 的 super() 应该被称为next-in-mro",因为它不一定向上调用父母;相反,它可以调用兄弟姐妹.

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

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

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

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

以下是一些参考资料,包括指向 Dylan 的 next-method 的链接,该方法用作 Python 的 super() 模型:

I was trying to understand how super works in python and tried the following example:

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()

fairly simple.. And I tried the following super calls(displayed with the results here):

>>> 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

I do not understand why does super(A,c).__init__() print out that its in B's init??

解决方案

Python's super() should have been been called "next-in-mro" because it doesn't necessarily call upwards to a parent; rather, it can call a sibling instead.

It is easy to inspect the method resolution order of your class structure:

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

You can see that B is the next class after A.

The reason for this design is that it lets the chain of super calls visit every class in the chain no more than once. That supports a style of programming called "cooperative multiple inheritance" which is sometimes very useful.

Here are some references including links to Dylan's next-method that served as a model for Python's super():

这篇关于在 python 中揭开 super 的神秘面纱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆