' STR'尝试设置对象属性时,对象不可调用

时间:2015-12-15 20:52:48

标签: python

有这样的对象

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

为什么我无法设置属性__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

我使用2.7.6 Python

1 个答案:

答案 0 :(得分:3)

属性的语法看起来像普通的属性访问(按设计)。

这是属性装饰器的主要用例,用于精确创建“托管属性”,因此您不必为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

这是所有记录的here

注意:通常在python中,您将“非托管”属性存储为self._x,而不是self.__x

相关问题