简体   繁体   English

使用 @property 和 @setter 装饰器时出现递归错误

[英]Recursion error when using the @property and @setter decorators

class Phone:
    def __init__(self,brand,model_name,price):
        self.brand = brand
        self.model_name = model_name
        self.price = price 
    @property
    def price(self):
        return self.price 
    @price.setter
    def price(self,new_value):
        self.price = max(new_value,0)


p1 = Phone('Asus','Asus10',102000)
print(p1.price)

Error:错误:

RecursionError: maximum recursion depth exceeded RecursionError:超出最大递归深度

The property name and the field names are the same.属性名称和字段名称相同。 Adding an underscore before the field name can fix it.在字段名称前添加下划线可以修复它。

class Phone:
    def __init__(self,brand,model_name,price):
        self.brand = brand
        self.model_name = model_name
        self._price = price 
    @property
    def price(self):
        return self._price 
    @price.setter
    def price(self,new_value):
        self._price = max(new_value,0)


p1 = Phone('Asus','Asus10',102000)
print(p1.price)

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

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