Python pattern for defaulting to a 'grandparent' class's implementation

时光总嘲笑我的痴心妄想 提交于 2020-01-05 02:30:26

问题


class Thing(object):
  def sound(self):
    return '' #Silent

class Animal(Thing):
  def sound(self):
    return 'Roar!'

class MuteAnimal(Animal):
   def sound(self):
    return '' #Silent

Is there a pattern in python for MuteAnimal's sound to refer to its grandparent class Thing's implementation? (eg super(MuteAnimal,self).super(Animal.self).sound() ?) Or is Mixin a better use case here?


回答1:


As said by Alexander Rossa in Python inheritance - how to call grandparent method? :

There are two ways to go around this:

Either you can use explicitly A.foo(self) method as the others have suggested - use this when you want to call the method of the A class with disregard as to whether A is B's parent class or not:

class C(B):   def foo(self):
    tmp = A.foo(self) # call A's foo and store the result to tmp

return "C"+tmp 

Or, if you want to use the .foo() method of B's parent class regardless whether the parent class is A or not, then use:

class C(B):   def foo(self):
    tmp = super(B, self).foo() # call B's father's foo and store the result to tmp
    return "C"+tmp



回答2:


Is it sensible to do this?

In MuteAnimal.sound, call super(Animal, self).sound()

because Animal is in fact, gradparent class of MuteAnimal...



来源:https://stackoverflow.com/questions/42937114/python-pattern-for-defaulting-to-a-grandparent-classs-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!