Using Properties in Python classes cause “maximum

2020-04-02 06:28发布

Here is a test class that I wrote to became familiar with @properties and setter functionality in Python script:

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

The problems is that when I want to create an object from my class, I face the following error:

>>> 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
>>> 

2条回答
干净又极端
2楼-- · 2020-04-02 07:14

You are using the same name for the getter, setter and attribute. When setting up a property, you must rename the attribute locally; the convention is to prefix it with an underscore.

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

    @property
    def x(self):
        return self._x
查看更多
相关推荐>>
3楼-- · 2020-04-02 07:26

The problem is in these lines:

def x(self):
    return self.x

Replace it with

def get_x(self):
    return self.x

Because now the function calls itself, leading to the recursion depth exceeded.

查看更多
登录 后发表回答