下面是测试类,我写的逐渐熟悉@properties和setter功能的Python脚本:
@properties
setter
class Test(object): def __init__(self, value): self.x = value @property def x(self): return self.x @x.setter def x(self, value): self.x = value
问题是,当我想从类中创建对象时,会遇到以下错误:
>>> t = Test(1) Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> t = Test(1) File "<pyshell#18>", line 3, in __init__ self.x = value File "<pyshell#18>", line 9, in x self.x = value File "<pyshell#18>", line 9, in x #A bunch of lines skipped RuntimeError: maximum recursion depth exceeded >>>
您正在为getter,setter和attribute使用相同的名称。设置属性时,必须在本地重命名该属性;约定是用下划线作为前缀。
class Test(object): def __init__(self, value): self._x = value @property def x(self): return self._x