问题
Having such object
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
Why I can not set attribute __x
? Here is a traceback
>>> 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
I'm using 2.7.6 Python
回答1:
The syntax for properties looks like normal attribute access (by design).
It's the main use case of the property decorator, for creating "managed attributes" precisely so that you don't have to use function call syntax for getters and setters:
a.x()
just becomesa.x
a.x(11)
just becomesa.x = 11
Ergo:
>>> a = testDec()
>>> a.x
called getter
'stuff'
>>> a.x = 123
called setter
>>> a.x
called getter
123
This is all documented here.
Note: usually in python you would store the "unmanaged" attribute as self._x
, not self.__x
.
来源:https://stackoverflow.com/questions/34299172/str-object-is-not-callable-when-trying-to-set-object-property