简体   繁体   English

使用@property装饰器时出现RecursionError

[英]RecursionError when using @property decorator

I am learning the @property manipulation and writing some codes as below, while the cmd just shows, 我正在学习@property操作并编写以下代码,而cmd仅显示,

Traceback (most recent call last):
File "C:\Users\mckf1\pyfile\new.py", line 23, in <module>
s.width=1024
File "C:\Users\mckf1\pyfile\new.py", line 9, in width
self.width=value1
File "C:\Users\mckf1\pyfile\new.py", line 9, in width
self.width=value1
File "C:\Users\mckf1\pyfile\new.py", line 9, in width
self.width=value1
[Previous line repeated 495 more times]
RecursionError: maximum recursion depth exceeded

However, after I add one lower dash in front of the arguments (width, height, resolution), the codes fuction normally. 但是,在参数(宽度,高度,分辨率)前面加一个下划线后,代码正常工作。 I don't understand why. 我不明白为什么。

class Screen(object):
    @property
    def width(self):
        return self.width
    @width.setter
    def width(self,value1):
        if value1<=10 or value1>=10000:
            print(value1,'is not a proper width')
        else:
            self.width=value1
    @property
    def height(self):
        return self.height
    @height.setter
    def height(self,value2):
        if value2<=5 or value2>=5000:
            print(value2,'is not a proper height')
        else:
            self.height=value2
    @property
    def resolution(self):
        self.resolution=self.width*self.height
        print(self.width,'*',self.height,'= %d'%self.resolution)
s=Screen()
s.width=1024
s.height=768
s.resolution

Decorators are not ignored when accessing the property from within the class. 从类内部访问属性时,不会忽略装饰器。 So when the width() method does 所以当width()方法

return self.width

that invokes the width() method again, which tries to return self.width , which invokes the method, and so on and so one. 再次调用width()方法,该方法尝试return self.width ,后者调用该方法,依此类推。

This is why you need to use different names for the properties internally to the class than the names of the decorator methods. 这就是为什么您需要为类内部的属性使用与装饰器方法的名称不同的名称。

@property
def width(self):
    return self._width

Accessing the _width property doesn't try to use the decorated method, so you don't get into an infinite recursion. 访问_width属性不会尝试使用修饰的方法,因此您不会陷入无限递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM