我似乎无法弄清楚多重继承的问题。这是一个非常抽象的最小示例,它重现了我的错误(我的代码比这复杂得多)。
class Thing(object):
def __init__(self, x=None):
self.x = x
class Mixin(object):
def __init__(self):
self.numbers = [1,2,3]
def children(self):
return [super().__init__(x=num) for num in self.numbers]
class CompositeThing(Mixin, Thing):
def __init__(self):
super().__init__()
def test(self):
for child in self.children():
print(child.x)
obj = CompositeThing()
obj.test()
[this,我希望children()
方法返回从Thing
建立的self.numbers
列表。相反,我得到了TypeError: super(type, obj): obj must be an instance or subtype of type
。顺便说一句,如果我不调用构造函数并允许子级返回super()
3次(即,未实例化的超类),也会发生同样的事情。任何想法为什么会发生这种情况?
提前感谢!
在代码的第9行中,您似乎正在尝试调用__init__
的object
。我假设您要从Mixin
继承Thing
。
class Thing(object):
def __init__(self, x=None):
self.x = x
class Mixin(Thing):
def __init__(self):
self.numbers = [1,2,3]
def children(self):
return [super().__init__(x=num) for num in self.numbers] # Now calls Thing.__init__ instead of object.__init__
class CompositeThing(Mixin, Thing):
def __init__(self):
super().__init__()
def test(self):
for child in self.children():
print(child.x)
obj = CompositeThing()
obj.test()
实际上,我知道了。有两个问题:(1)super()
doesn't work as expected inside comprehensions,因为Py3中的理解有其自身的范围-这导致我遇到的super()
。 (2)我实际上试图做的是TypeError
,而不是从父级调用方法。为了清楚起见,我为后一个问题发布了一个新问题。