小编典典

在Python类中使用属​​性会导致“超出最大递归深度”

python

下面是测试类,我写的逐渐熟悉@propertiessetter功能的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
>>>

阅读 210

收藏
2020-12-20

共1个答案

小编典典

您正在为getter,setter和attribute使用相同的名称。设置属性时,必须在本地重命名该属性;约定是用下划线作为前缀。

class Test(object):
    def __init__(self, value):
        self._x =  value

    @property
    def x(self):
        return self._x
2020-12-20