在python类中获取RecursionError

时间:2019-05-15 19:03:17

标签: python

我在Python中定义了一个Product类,如下所示:

var int_string = new DoubleIndexer<int, string>();
int_string[1] = "Hello"; // OK
int_string["Hello"] = 1; // OK

var int_byte = new DoubleIndexer<int, byte>();
int_byte[1] = 13; // OK
int_byte[(byte)13] = 1; // OK

当我尝试设置产品(产品)的新实例的价格属性时:

class Product:
    @property
    def price(self):
        return self.price

    @price.setter
    def price(self, value):
        if value < 10:
            raise ValueError("price can't be negative")
        self.price = value

我收到一条错误消息:

  

RecursionError:超过最大递归深度

有人可以在这里解释我做错了吗...

2 个答案:

答案 0 :(得分:5)

递归在这里发生:

@price.setter
def price(self, value):
    self.price = value

其中的self.price =将触发与设置程序相同的price()函数。更好的方式(即更常规的方式)是使用self._price来保持您的价值。

答案 1 :(得分:1)

    self.price = value

这是对setter本身的递归引用。查找如何编写二传手;您会看到问题所在。您需要引用伪私有变量:

    self._price = value