因此,我正在使用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
我认为这意味着将其视为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
>>> t.x
t.x
5
显然,第一个调用按预期工作,因为我调用了getter,并且没有默认值,并且失败。好,很好,我了解。但是,对assign的调用t.x = 5似乎会创建一个新属性x,而现在getter无效!
我想念什么?
largeQ
交互式爱情
相关分类