cos*_*mer 28 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?
Run Code Online (Sandbox Code Playgroud)
Sea*_*ira 33
如果你总是想要Grandfather#do_thing
,不管是否Grandfather
是Father
直接的超类,那么你可以显式调用Grandfather#do_thing
该Son
self
对象:
class Son(Father):
# ... snip ...
def do_thing(self):
Grandfather.do_thing(self)
Run Code Online (Sandbox Code Playgroud)
另一方面,如果你想调用超类的do_thing
方法Father
,不管Grandfather
你是否应该使用super
(如Thierry的答案):
class Son(Father):
# ... snip ...
def do_thing(self):
super(Father, self).do_thing()
Run Code Online (Sandbox Code Playgroud)
Thi*_* J. 20
你可以这样做:
class Son(Father):
def __init__(self):
super(Son, self).__init__()
def do_thing(self):
super(Father, self).do_thing()
Run Code Online (Sandbox Code Playgroud)