Python的多重继承: Picking which super() to call

标签 python multiple-inheritance super

在 Python 中,我如何选择调用哪个 Parent 的方法?假设我想调用父 ASDF2 的 __init__ 方法。好像我必须在 super() 中指定 ASDF1 ..?而如果我想调用ASDF3的__init__,那么我必须指定ASDF2?!

>>> class ASDF(ASDF1, ASDF2, ASDF3):
...     def __init__(self):
...         super(ASDF1, self).__init__()
            
>>> ASDF()
# ASDF2's __init__ happened

>>> class ASDF(ASDF1, ASDF2, ASDF3):
...     def __init__(self):
...         super(ASDF2, self).__init__()

>>> ASDF()
# ASDF3's __init__ happened

对我来说似乎很疯狂。我做错了什么?

最佳答案

那不是 super()是为了。 Super 基本上按特定顺序选择一个(或全部)它的 parent 。如果你只想调用单亲的方法,这样做

class ASDF(ASDF1, ASDF2, ASDF3):
    def __init__(self):
        ASDF2.__init__(self)

关于Python的多重继承: Picking which super() to call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14206015/

相关文章:

python - 简单程序中的错误: TypeError: into object has no attribute '__getitem__'

Python Pyx 绘图 : Using\mathbb in axes label of plot

c++ - C++中,为什么指针转换时地址变了?

c++ - 多重继承析构函数调用他自己和父析构函数? C++

java - 不想在子类中使用构造函数

java - 什么是PECS(生产者扩展了 super 消费者)?

python - 我该如何修改这段代码,以便它能正确打印图案?

python - Python 中最长的递增子序列(For vs While 循环)

c++ - C++接口(interface)多重继承中的歧义

python - 为什么在父类 __init__() 中调用 super() 会改变子类 __init__() 的行为?