在Mixin中调用超类的设置器 [英] Calling the setter of a super class in a mixin
本文介绍了在Mixin中调用超类的设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下(在生物学上不是很正确)的类:
Suppose I have the following (not quite biologically correct) classes:
class AnimalBaseClass:
def __init__(self):
self._limbs = None
@property
def limbs(self):
return self._limbs
@limbs.setter
def limbs(self, value):
self.paws = value
self._limbs = value
class BipedalMixIn:
@property
def limbs(self):
return super().limbs
@limbs.setter
def limbs(self, value):
self.bipedal = (value == 2)
# does not work
super().limbs = value
此处super().limbs = value
是 Python不支持的.如果BipedalMixIn
不是mixin,我可以直接使用超类的名称,但是有什么简单的选择可以在mixin中调用超类的setter?
Here super().limbs = value
is not supported by python. If BipedalMixIn
was not a mixin, I could use the super class's name directly, but is there any simple alternative, to call the super class's setter in a mixin?
推荐答案
尽管可以使用任何更简单的答案,但仍可以进行以下工作.
The following works, although any simpler answers are appreciated.
class AnimalBaseClass:
def __init__(self):
self._limbs = None
@property
def limbs(self):
return self._limbs
@limbs.setter
def limbs(self, value):
self.paws = value
self._limbs = value
class BipedalMixIn:
@property
def limbs(self):
return super().limbs
@limbs.setter
def limbs(self, value):
self.bipedal = (value == 2)
# works!
super(BipedalMixIn, self.__class__).limbs.__set__(self, value)
class Bird(BipedalMixIn, AnimalBaseClass):
pass
bird = Bird()
bird.limbs = 2
print(bird.bipedal) # True
print(bird.paws) # 2
这篇关于在Mixin中调用超类的设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文