【问题标题】:'str' object is not callable when trying to set object property尝试设置对象属性时,“str”对象不可调用
【发布时间】:2016-03-21 19:56:25
【问题描述】:

有这样的对象

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

【问题讨论】:

  • 如果你想设置a.x,你不应该设置a.x = 11吗?

标签: python properties


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2011-06-07
    相关资源
    最近更新 更多