python - 为什么没有调用所有基类构造函数?

标签 python python-2.7

在 Python 2.7.10 中

class OneMixin(object):
    def __init__(self):
        # super(OneMixin, self).__init__()
        print "one mixin"

class TwoMixin(object):
    def __init__(self):
        # super(TwoMixin, self).__init__()
        print "two mixin"

class Account(OneMixin, TwoMixin):
    def __init__(self):
        super(Account, self).__init__()
        print "account"

Account.mro() 是:[<class 'Account'>, <class 'OneMixin'>, <class 'TwoMixin'>, <type 'object'>]

尽管 MRO 中列出了每个类,但并未打印“两个 mixin”。

如果我取消注释 OneMixin 和 TwoMixin 中的 super 调用,MRO 完全相同,但会打印“两个 mixin”。

为什么有区别?我希望 MRO 中的所有内容都会被调用。

最佳答案

这是因为 super 用于将调用委托(delegate)给某个类型的父类或同级类。 Python documentation第二个用例的描述如下:

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

如果您从 OneMixin 中删除 super 调用,则不会将该调用委托(delegate)给 MRO 中的下一个类型。

关于python - 为什么没有调用所有基类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39939737/

相关文章:

python - 跳棋算法 : how to reduce nested for loops

python - 如何在应用程序的 urls.py 中设置通用 View ?

java - 如何从文本文档中预测连续值(时间)?

PythonNet 文件未找到异常 : Unable to find assembly

python - 在不使用临时变量的情况下交换类中的变量

python - 从列表列表创建单个列表

python - 带有证书 SSLv3 的 URLLib 警报握手失败

python - Python 中推荐的缩进大小是多少?

python-2.7 - 构建 core-image-minimal.bb 时如何包含 poky/meta/lib/oe/image.py ?

python - 在这种情况下如何配置 __init__.py?