38

如果一个方法被另一个类覆盖,你如何在继承链上调用一个方法而不是一个类?

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?
4

2 回答 2

46

如果您总是想要Grandfather#do_thing,无论是否GrandfatherFather的直接超类,那么您都可以Grandfather#do_thingSon self对象上显式调用:

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

另一方面,如果您想调用的超类的do_thing方法Father,无论是否Grandfather应该使用super(如蒂埃里的回答):

class Son(Father):
    # ... snip ...
    def do_thing(self):
        super(Father, self).do_thing()
于 2013-08-08T04:47:18.637 回答
30

您可以使用以下方法执行此操作:

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

    def do_thing(self):
        super(Father, self).do_thing()
于 2013-08-08T04:48:01.210 回答