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?
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)
另一方面,如果你想调用超类的do_thing方法Father,不管Grandfather你是否应该使用super(如Thierry的答案):
class Son(Father):
    # ... snip ...
    def do_thing(self):
        super(Father, self).do_thing()
Thi*_* J. 20
你可以这样做:
class Son(Father):
    def __init__(self):
        super(Son, self).__init__()
    def do_thing(self):
        super(Father, self).do_thing()
| 归档时间: | 
 | 
| 查看次数: | 11644 次 | 
| 最近记录: |