调用父母的父方法,该方法已由父母重写 [英] 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?
推荐答案
如果你总是想要祖父#do_thing
,无论祖父
是父
的直接超类,那么你可以明确在 Son
self
对象上调用祖父#do_thing
:
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)
另一方面,如果你想调用父
的超类的 do_thing
方法,无论是祖父
你应该使用 super
(如在Thierry的回答中):
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()
这篇关于调用父母的父方法,该方法已由父母重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文