【发布时间】:2016-08-24 04:57:04
【问题描述】:
这是我编写的一个测试类,用于熟悉 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
>>>
【问题讨论】:
-
使用
self._x而不是self.x作为私人成员。通过同时命名成员和属性x属性阴影成员,并在 getter 正文中调用return self.x。
标签: python python-3.x python-2.7 class