调用父类的父类方法,该方法已被子类覆盖

46
如何在继承链中调用一个方法,如果这个方法已经被其他类重写了?
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?

        # How to call Grandfather's do_thing() here?
2个回答

53

如果您总是想要调用Grandfather#do_thing,不管Grandfather是否是Father的直接超类,那么您可以在Son self对象上显式调用Grandfather#do_thing

class Son(Father):
    # ... snip ...
    def do_thing(self):
        Grandfather.do_thing(self)

另一方面,如果你想调用Father的超类的do_thing方法,无论它是不是Grandfather,你都应该使用super(如Thierry的答案中所示):

class Son(Father):
    # ... snip ...
    def do_thing(self):
        super(Father, self).do_thing()

3
你的答案比Thierry J的更好吗? - outis nihil
9
如果您始终想要“Grandfather”,而不管它是“Father”的直接超类,那么请使用这个。如果您想要“Father”的超类,而不管它是否为“Grandfather”,则请使用Thierry的方法。 - Sean Vieira

34

您可以使用以下方法来实现此操作:

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

    def do_thing(self):
        super(Father, self).do_thing()

3
根据@Sean Vieira的评论,在这种情况下,您将使用直接父类的超类的“do_thing”方法,这并不能保证它是“Grandfather”的方法(在多重继承的情况下)。 - Hamlett
属性错误:'super'对象没有属性 - CS QGB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接