如何解决如何动态调用每个父级的 __init__
我读过the most similar question on SO to my question,它是关于单亲继承的,唯一提到多父继承的答案建议读者使用调用的静态形式 那个方法 (SomeSuperClass.someMethod(self,args)
),as pointed out in the comments 并不总是干净的。
我要求一种方法来调用特定超类 someMethod
动态的特定方法 SomeSuperClass
,例如:
class SomeSuperClass():
def someMethod(self,args):
print("Hello,",end="")
class Subclass(SomeSuperClass,OtherSuperClass):
def someMethod(self,args):
# static calling (I do not want this solution)
SomeSuperClass.someMethod(self,args)
# dynamic calling (I want this one)
(my SomeSuperClass-ness).someMethod(args)
print("world!")
这是我实际测试过并想要工作的代码:
class Something():
def __init__(self,a,b) -> None:
self.sum = a+b
class SomethingElse():
def __init__(self,c,d) -> None:
self.product = c * d
class Both(Something,SomethingElse):
def __init__(self,b) -> None:
# sadly this does not work
super(Something,self).__init__(a,b)
super(SomethingElse,b)
# the following works,but is static and does not use super
# Something.__init__(self,b)
# SomethingElse.__init__(self,b)
b = Both(10,20)
print(b.sum,b.product)
运行此代码会导致以下错误:
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
显然它正在尝试调用 __init__
的 object
。在这种情况下,我如何正确使用 super
以使其实际调用适当的 __init__
?
解决方法
super()
函数将在您指定的之后委托给父级 - 参见 here,特别是以下备注:
对象或类型决定了要搜索的方法解析顺序。 搜索从 type
之后的课程开始。
所以要正确使用它,您应该使用super()
来指代Something
,使用super(Something,self)
来指代SomethingElse
;您可以通过阅读 __mro__
类的 Both
属性来查看顺序:
class Something():
pass
class SomethingElse():
pass
class Both(Something,SomethingElse):
pass
print(Both.__mro__)
哪个会告诉你顺序:
(<class '__main__.Both'>,<class '__main__.Something'>,<class '__main__.SomethingElse'>,<class 'object'>)
并解释为什么您最终会在第二次调用 object.__init__
时调用 super(...).__init__(...)
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。