Calling a parent's parent's method, which has been overridden by the parent

后端 未结 2 997
后悔当初
后悔当初 2020-12-29 02:33

How do you call a method more than one class up the inheritance chain if it\'s been overridden by another class along the way?

class Grandfather(object):
            


        
相关标签:
2条回答
  • 2020-12-29 02:54

    If you always want Grandfather#do_thing, regardless of whether Grandfather is Father's immediate superclass then you can explicitly invoke Grandfather#do_thing on the Son self object:

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

    On the other hand, if you want to invoke the do_thing method of Father's superclass, regardless of whether it is Grandfather you should use super (as in Thierry's answer):

    class Son(Father):
        # ... snip ...
        def do_thing(self):
            super(Father, self).do_thing()
    
    0 讨论(0)
  • 2020-12-29 02:59

    You can do this using:

    class Son(Father):
        def __init__(self):
            super(Son, self).__init__()
    
        def do_thing(self):
            super(Father, self).do_thing()
    
    0 讨论(0)
提交回复
热议问题