Python super在多级继承中的应用
我有一个代码如下:Python super在多级继承中的应用,python,python-3.x,Python,Python 3.x,我有一个代码如下: class A(): def something(): #Do something class B(A): def something(): super(B, self).something() #Do something class C(B): def something(): if VeryRareSpecificCase: super(super(C,se
class A():
def something():
#Do something
class B(A):
def something():
super(B, self).something()
#Do something
class C(B):
def something():
if VeryRareSpecificCase:
super(super(C,self)).something()
else:
super(C, self).something()
#Do something
但是,它会引发错误TypeError:必须是type,而不是super。如果您没有使用复杂的菱形继承,您可以使用以下方法跳过链中的父级:
class C(B):
def something(self):
if VeryRareSpecificCase:
super(B, self).something() # <-- note: B passed explicitly!
else:
super().something()
C类(B类):
定义某物(自我):
如果是特定情况:
super(B,self).something()#B-->A-->对象
,如MCVE中所示,这应该是安全的。然而,若您有比这更复杂的事情,那个么您必须直接使用,并精确地指定您需要手动执行的行为 你希望super(super(C,self))是指什么?如果答案是super(B,self)
,那么您没有正确使用super
;您应该只对类引用进行硬编码。在继承之前,我正在从另一个模块导入B,而A位于我不想访问的模块中。这会影响什么吗?或者我还能这样做吗?