你创建了一个属性
无法删除
以下内容:
>>> f = Foo2('bar')
>>> f.prop
'bar'
>>> f.prop = 'spam'
>>> f.prop
'spam'
>>> del f.prop
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't delete attribute
将此与
Foo().prop
属性,可以删除:
>>> f = Foo('bar')
>>> f.prop
'bar'
>>> del f.prop
>>> f.prop
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'prop'
除此之外,或者如果您添加了
@prop.deleter
处理程序,创建这样的属性实际上没有任何好处。将普通属性访问所能做的委托给函数并没有那么有用。
属性setter或getter在使用时更有用
另外的东西
只需设置属性,比如验证或转换。
例如,setter可以强制值始终为整数,包括在转换为整数失败时设置默认值:
@prop.setter
def prop(self, value):
try:
self._prop = int(prop)
except ValueError:
self._prop = 0
在其他编程语言(如java)中,如果不必在代码基中的任何地方重新编写对这些属性的所有访问权限,就无法轻松地将属性转换为getter和setter(java中没有与python属性等效的概念),因此在这些语言中,您经常会看到建议,从getter和setter开始。
这不适用于python
您可以将现有属性简单地转换为属性,而不必使用这些属性更改任何代码。