在python2使用@property属性时,出现了如下错误,
class Screen(object):File "/home/eason/learncode/test/test.py", line 7, in width
self.width=value
RuntimeError: maximum recursion depth exceeded
以下是代码:
class Screen(object):
@property
def width(self):
return self.width
@width.setter
def width(self, value):
self.width = value
@property
def height(self):
return self.height
@height.setter
def height(self, value):
self.height = value
@property
def resolution(self):
return self.width*self.height
s = Screen()
s.width = 1024
s.height = 768
print(s.resolution)
测试发现三个细节:
- 发现@property装饰的方法的属性必须为一个下划线开头。例如self.height改成self._height
- python3没有这个问题
- python2.7如果Screen类不继承object也没有问题