调用父级的父方法,该方法已由父级重写

cos*_*mer 28 python oop inheritance

如果在继承链中被另一个类覆盖,那么如何在继承链上调用多个类的方法呢?

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):
        # how to be like Grandfather?
Run Code Online (Sandbox Code Playgroud)

Sea*_*ira 33

如果你总是想要Grandfather#do_thing,不管是否GrandfatherFather直接的超类,那么你可以显式调用Grandfather#do_thingSon self对象:

class Son(Father):
    # ... snip ...
    def do_thing(self):
        Grandfather.do_thing(self)
Run Code Online (Sandbox Code Playgroud)

另一方面,如果你想调用超类的do_thing方法Father,不管Grandfather你是否应该使用super(如Thierry的答案):

class Son(Father):
    # ... snip ...
    def do_thing(self):
        super(Father, self).do_thing()
Run Code Online (Sandbox Code Playgroud)

  • 如果你总是想要"祖父",请使用这个,不管它是否是"父亲"的直接超类.如果你想要'父亲'的超级课程,请使用蒂埃里的,无论是否是"祖父". (6认同)
  • 有理由更喜欢你对Thierry J的回答吗? (3认同)

Thi*_* J. 20

你可以这样做:

class Son(Father):
    def __init__(self):
        super(Son, self).__init__()

    def do_thing(self):
        super(Father, self).do_thing()
Run Code Online (Sandbox Code Playgroud)

  • 按照@Sean Vieira 的评论,在这种情况下,您将使用直接父亲的超类的“do_thing”方法,但不能保证它将是“祖父的方法”(在多重继承的情况下) (2认同)