在 Python 类中使用属性会导致"maximum recursion depth exceeded"



下面是我编写的一个测试类,它熟悉了Python脚本中的@propertiessetter功能:

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

问题出在以下几行:

def x(self):
    return self.x

更换为

def get_x(self):
    return self.x

因为现在函数调用自己,导致递归深度超出。

相关内容

最新更新