38

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):
    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?
cosmo_kramer
  • 649
  • 2
  • 6
  • 12

2 Answers2

46

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()
Sean Vieira
  • 148,604
  • 32
  • 306
  • 290
  • 3
    is there a reason to prefer your answer to Thierry J's? – outis nihil Apr 10 '15 at 21:23
  • 9
    Use this one if you always want `Grandfather`, regardless of whether it is `Father`'s immediate superclass. Use Thierry's if you want `Father`'s superclass, regardless of whether it is `Grandfather`. – Sean Vieira Apr 10 '15 at 21:30
30

You can do this using:

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

    def do_thing(self):
        super(Father, self).do_thing()
Thierry J.
  • 2,061
  • 14
  • 23
  • 2
    Following the comment of @Sean Vieira, in this case you will use the 'do_thing' method of the immediate Father's superclass what doesn't assure that it will be the 'Grandfather's method (in case of multi inherence) – Hamlett Feb 12 '16 at 14:59