【发布时间】:2015-11-01 14:52:42
【问题描述】:
我有一个叫做节点的东西。 Definition 和 Theorem 都是一种节点,但只有 Definitions 应该被允许有plural 属性:
class Definition(Node):
def __init__(self,dic):
self.type = "definition"
super(Definition, self).__init__(dic)
self.plural = move_attribute(dic, {'plural', 'pl'}, strict=False)
@property
def plural(self):
return self._plural
@plural.setter
def plural(self, new_plural):
if new_plural is None:
self._plural = None
else:
clean_plural = check_type_and_clean(new_plural, str)
assert dunderscore_count(clean_plural)>=2
self._plural = clean_plural
class Theorem(Node):
def __init__(self, dic):
self.type = "theorem"
super().__init__(dic)
self.proofs = move_attribute(dic, {'proofs', 'proof'}, strict=False)
# theorems CANNOT have plurals:
# if 'plural' in self:
# raise KeyError('Theorems cannot have plurals.')
如您所见,定义有plural.setter,但定理没有。但是,代码
theorem = Theorem(some input)
theorem.plural = "some plural"
运行良好并且不会引发错误。但我希望它引发错误。如您所见,我尝试在显示的代码底部手动检查复数,但这只是一个补丁。我想阻止任何未明确定义的属性的设置。这种事情的最佳做法是什么?
我正在寻找满足“chicken" requirement:”的答案:
我认为这不能解决我的问题。在你的两个解决方案中,我都可以 附加代码 t.chicken = 'hi'; print(t.chicken),它会打印 hi 没有错误。我不希望用户能够编造新的 像鸡一样的属性。
【问题讨论】:
-
如果你实现你所要求的,你将无法设置
self._plural,因为它没有设置器。在我们的工作中牢记这些内容很重要。
标签: oop python-3.x inheritance