super() 的多重继承问题
Multiple inheritance problem with super()
我遇到了一个我似乎无法弄清楚的多重继承问题。这是一个非常抽象的最小示例,它重现了我的错误(我的代码比这复杂得多)。
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()
方法能够 return 从 self.numbers
构建的 Thing
列表。相反,我得到 TypeError: super(type, obj): obj must be an instance or subtype of type
。顺便说一句,如果我不调用构造函数并允许 children 到 return super()
3 次(即未实例化的超类),也会发生同样的事情。任何想法为什么会发生这种情况?
提前致谢!
在代码的第 9 行中,您似乎正在尝试调用 object
的 __init__
。我假设你打算让 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) because comprehensions in Py3 have their own scope - this was causing the TypeError
I was experiencing. (2) What I was really trying to do was create a new instance of the parent,而不是从父级调用方法。为了清楚起见,我已经针对后一个问题发布了一个新问题。
我遇到了一个我似乎无法弄清楚的多重继承问题。这是一个非常抽象的最小示例,它重现了我的错误(我的代码比这复杂得多)。
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()
方法能够 return 从 self.numbers
构建的 Thing
列表。相反,我得到 TypeError: super(type, obj): obj must be an instance or subtype of type
。顺便说一句,如果我不调用构造函数并允许 children 到 return super()
3 次(即未实例化的超类),也会发生同样的事情。任何想法为什么会发生这种情况?
提前致谢!
在代码的第 9 行中,您似乎正在尝试调用 object
的 __init__
。我假设你打算让 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) TypeError
I was experiencing. (2) What I was really trying to do was create a new instance of the parent,而不是从父级调用方法。为了清楚起见,我已经针对后一个问题发布了一个新问题。