Ebr*_*Him 10 python class python-2.7 python-3.x
这是我编写的一个测试类,用于熟悉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
Run Code Online (Sandbox Code Playgroud)
问题是,当我想从我的类创建一个对象时,我面临以下错误:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
Reb*_*que 20
您对getter,setter和attribute使用相同的名称.设置属性时,必须在本地重命名该属性; 惯例是在它前面添加下划线.
class Test(object):
def __init__(self, value):
self._x = value
@property
def x(self):
return self._x
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4147 次 |
最近记录: |