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

时间:2013-08-08 04:35:21

标签: 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?

2 个答案:

答案 0 :(得分:31)

如果您始终需要Grandfather#do_thing,无论Grandfather是否为Father的直接超类,您都可以Grandfather#do_thing {{{{}} {{}} {{}} 1}}对象:

Son

另一方面,如果要调用self超类的class Son(Father): # ... snip ... def do_thing(self): Grandfather.do_thing(self) 方法,无论是do_thing,都应使用Father(如在蒂埃里的回答中):

Grandfather

答案 1 :(得分:20)

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

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

    def do_thing(self):
        super(Father, self).do_thing()
相关问题