相关疑难解决方法(0)

为什么Python中的@ foo.setter不适合我?

所以,我正在使用Python 2.6中的装饰器,我在使它们工作时遇到了一些麻烦.这是我的班级文件:

class testDec:

    @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像对待财产一样,但是在get和set上调用这些函数.所以,我解雇了IDLE并检查了它:

>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "testDec.py", line 18, in x
    return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> …
Run Code Online (Sandbox Code Playgroud)

python decorator new-style-class

153
推荐指数
4
解决办法
7万
查看次数

标签 统计

decorator ×1

new-style-class ×1

python ×1