在Python类中使用属性会导致“超过最大递归深度”。 [英] Using Properties in Python classes cause "maximum recursion depth exceeded"
本文介绍了在Python类中使用属性会导致“超过最大递归深度”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我编写的测试类,它熟悉Python脚本中的 @properties
和 setter
功能:
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
>>>
推荐答案
您正在为getter,setter使用相同的名称和属性。设置属性时,必须在本地重命名属性;
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
这篇关于在Python类中使用属性会导致“超过最大递归深度”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文