Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

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

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?
question from:https://stackoverflow.com/questions/18117974/calling-a-parents-parents-method-which-has-been-overridden-by-the-parent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...