下面是测试类,我写的逐渐熟悉了@properties
和setter
功能在Python脚本:使用属性造成“最大递归深度超过”
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
>>>
使用'self._x'而不是'self.x'作为私人成员。通过命名成员和属性'x'属性阴影成员,并且'get self.x'在getter体内调用它自己。 –