gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:39:12 24 4
gpt4 key购买 nike

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

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