基本上,我在这里询问的问题和一些答案,例如下面, Son
在其中做一些诸如 Father
(这种情况下的init)和其他一些诸如 GrandFather
的事情(do_thing
)。
class GrandFather(object):
def __init__(self):
pass
def do_thing(self):
# stuff
class Father(GrandFather):
def __init__(self):
super(Father, self).__init__()
def do_thing(self):
# stuff different than Grandfather stuff
class Son(Father):
def __init__(self):
super(Son, self).__init__()
def do_thing(self):
super(Father, self).do_thing() # <-- this line bypasses Father's implementation
我想知道的是,像这样调用 super
有任何后果(上面的最后一行),即传递除自己的类型的类型。我的意思是像您的代码在您不期望的一个奇怪的地方打破。
您要问的通常会起作用,但是在存在多个继承的情况下,它可能无法完全执行您打算的目标。例如,如果Son
也从Mother
类继承(由于乱伦也是Grandfather
的子类),则您不会从上一行中接到您的期望:
class GrandFather(object):
def do_thing(self):
print("Grandfather")
class Father(GrandFather):
def do_thing(self):
print("Father")
class Mother(GrandFather):
def do_thing(self):
print("Mother")
class Son(Father, Mother):
def do_thing(self):
super(Father, self).do_thing() # will print "Mother", not "Grandfather"
如果在Son
子类中添加了多个继承,甚至可能意外地出现此问题(例如,class GrandSon(Son, Mother): pass
使用您先前的Son
定义仅来自Father
)。
这可能是您想要的也可能不是您想要的。如果您想始终获得GrandFather
的do_thing
实现,则应明确调用GrandFather.do_thing(self)
,而不是尝试使用super
。
,但是要让课程绕过父母的方法,这通常不是一个好主意。通过重组您的代码,您可能会更好地为您服务。也许您可以将希望Son
的GrandFather.do_thing
部分分解为单独的方法。您无需在Father
中覆盖该方法,您不能从Father.do_thing
调用它。