默认为“祖父母”类的实现的Python模式

2024-10-02 14:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

python中是否有一个模式用于MuteAnimal的声音引用其祖父母类Thing的实现?(例如super(MuteAnimal,self).super(Animal.self).sound()?)或者Mixin是一个更好的用例?在


Tags: self声音returnobjectdef模式mixinclass
2条回答

正如Alexander RossaPython 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

这样做明智吗?在

MuteAnimal.sound中,调用super(Animal, self).sound()

因为动物实际上是互斥动物的父类。。。在

相关问题 更多 >