我收到错误:TypeError: __init__() 恰好需要 2 个参数(给定 3 个)
当试图从类 Top 实例化一个对象时:
super(Middle1, self).__init__(name, "middle")
class Base(object):
def __init__(self, name, type):
pass
class Middle1(Base):
def __init__(self, name):
super(Middle1, self).__init__(name, "middle1")
class Middle2(Base):
def __init__(self, name):
super(Middle2, self).__init__(name, "middle2")
class Middle3(Base):
def __init__(self, name):
super(Middle3, self).__init__(name, "middle3")
class Top(Middle1, Middle2, Middle3):
def __init__(self):
super(Top, self).__init__("top")
# Here is where it produces the error
if __name__ == '__main__':
Top()
我对这个多重继承问题不了解什么?
注意:这是python 2.7
编辑
好的,所以我尝试了一些我认为适合我的情况的方法。这是等效的最终结果,我认为它基本上是通过不调用 super 而是调用每个单独的 __init__ 来强制深度首先。
class Base(object):
def __init__(self, name, type):
pass
class Middle1(Base):
def __init__(self, name, type = "middle1"):
super(Middle1, self).__init__(name, type)
class Middle2(Base):
def __init__(self, name, type = "middle2"):
super(Middle2, self).__init__(name, type)
class Middle3(Base):
def __init__(self, name, type = "middle3"):
super(Middle3, self).__init__(name, type)
class Top(Middle1, Middle2, Middle3):
def __init__(self):
Middle1.__init__(self, "top")
Middle2.__init__(self, "top")
Middle3.__init__(self, "top")
# No errors anymore
if __name__ == '__main__':
Top()