'str' object is not callable when trying to set object property

风流意气都作罢 提交于 2020-11-29 08:50:20

问题


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 becomes a.x
  • a.x(11) just becomes a.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!