打电话给父母的父母的方法,有什么后果吗?



基本上,我在这里询问的问题和一些答案,例如下面, 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)。

这可能是您想要的也可能不是您想要的。如果您想始终获得GrandFatherdo_thing实现,则应明确调用GrandFather.do_thing(self),而不是尝试使用super

,但是要让课程绕过父母的方法,这通常不是一个好主意。通过重组您的代码,您可能会更好地为您服务。也许您可以将希望SonGrandFather.do_thing部分分解为单独的方法。您无需在Father中覆盖该方法,您不能从Father.do_thing调用它。

最新更新