gpt4 book ai didi

默认为 'grandparent' 类实现的 Python 模式

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:30 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

Alexander Rossa 所说在 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

关于默认为 'grandparent' 类实现的 Python 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42937114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com