下面是測試類,我寫的逐漸熟悉了@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體內調用它自己。 –