有这样的对象
class testDec(object):
def __init__(self):
self.__x = 'stuff'
@property
def x(self):
print 'called getter'
return self.__x
@x.setter
def x(self, value):
print 'called setter'
self.__x = value
Run Code Online (Sandbox Code Playgroud)
为什么我不能设置属性__x?这是一个追溯
>>> a.x
called getter
'stuff'
>>> a.x(11)
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)
我正在使用 2.7.6 Python
属性的语法看起来像正常的属性访问(按设计)。
这是属性装饰器的主要用例,用于精确创建“托管属性”,以便您不必对 getter 和 setter 使用函数调用语法:
a.x() 就变成 a.x a.x(11) 就变成 a.x = 11 因此:
>>> a = testDec()
>>> a.x
called getter
'stuff'
>>> a.x = 123
called setter
>>> a.x
called getter
123
Run Code Online (Sandbox Code Playgroud)
这都记录在此处。
注意:通常在 python 中,您会将“非托管”属性存储为self._x,而不是self.__x。