覆盖继承的属性设置器 [英] Overriding an inherited property setter
问题描述
我有一个叫做Node
的类,下面有一个importance
setter和getter:
I have a class called Node
that has an importance
setter and getter, below:
class Node:
@property
def importance(self):
return self._importance
@importance.setter
def importance(self, new_importance):
if new_importance is not None:
new_importance = check_type_and_clean(new_importance, int)
assert new_importance >= 1 and new_importance <= 10
self._importance = new_importance
稍后,我有一个从Node
继承的类Theorem
.就importance
而言,Theorem
和Node
之间的唯一区别是Theorem
的importance
必须至少为3
.
Later on, I have a class Theorem
that inherits from Node
. The only difference between a Theorem
and a Node
, as far as importance
is concerned, is that a Theorem
must have an importance
of at least 3
.
定理如何继承 importance
设置器,但要添加importance >= 3
的附加约束?
How can a Theorem inherit the importance
setter, but add on the additional constraint that importance >= 3
?
我尝试过这种方式:
class Theorem(Node):
@importance.setter
def importance(self, new_importance):
self.importance = new_importance # hoping this would use the super() setter
assert self.importance >= 3
推荐答案
您可以直接通过Node
类引用现有属性,并使用该属性的setter
方法从中创建一个新属性:>
You can refer to the existing property directly through the Node
class, and use the property's setter
method to create a new property from it:
class Theorem(Node):
@Node.importance.setter
def importance(self, new_importance):
# You can change the order of these two lines:
assert new_importance >= 3
Node.importance.fset(self, new_importance)
这将在Theorem
类中创建一个新属性,该属性使用Node.importance
中的getter方法,但将setter方法替换为其他属性.
属性通常就是这样工作的:调用属性的setter
会返回带有自定义设置器的新属性,该设置器通常仅替换旧属性.
This will create a new property into Theorem
class that uses the getter method from Node.importance
but replaces the setter method with a different one.
That's how properties in general work: calling a property's setter
returns a new property with a custom setter, which usually just replaces the old property.
您可以通过阅读此答案(还有问题)来了解有关属性工作原理的更多信息.
You can learn more about how properties work by reading this answer (and the question too).
这篇关于覆盖继承的属性设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!