Python - 不使用私有成员时的错误消息[重复]

问题描述 投票:0回答:1

运行以下命令时出现错误:

class Product:
def __init__(self, price):
    self.setprice(price)
def getprice(self):
    return self.price
def setprice(self, value):
    if value < 0:
        raise ValueError("Price cannot be negative")
    self.price = value
price = property(getprice, setprice)

x = 产品(23) 打印(x.价格)

错误如下:

File "c:\Users\OneDrive\Desktop\PYTHON\tempCodeRunnerFile.py", line 9, in setprice self.price = value [Previous line repeated 993 more times] File "c:\Users\OneDrive\Desktop\PYTHON\tempCodeRunnerFile.py", line 7, in setprice if value < 0: RecursionError: maximum recursion depth exceeded in comparison

但是当我将价格定为私人会员时,它运行正常:

class Product:
def __init__(self, price):
    self.setprice(price)
def getprice(self):
    return self.__price
def setprice(self, value):
    if value < 0:
        raise ValueError("Price cannot be negative")
    self.__price = value
price = property(getprice, setprice)

x = 产品(23) 打印(x.价格)

谁能告诉我为什么会出现这个错误???为什么我们需要在 setprice 方法中将价格设为私有?

python python-3.x properties runtime-error private-members
1个回答
0
投票

使用

property
定义属性的正确方法是:

class Product
    def __init__(self, price):
        self.price = price
    @property
    def price(self):
        return self._price
    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("Price can't be negative.")
        self._price = value

然后你就可以按照你的预期使用它了:

>>> p = Product(3)
>>> p.price
3
>>> p.price = -1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in price
ValueError: Price can't be negative.
>>> p.price
3
>>> p.price = 4
>>> p.price
4
>>>

您的错误源于这样一个事实:当您定义

self.price = ...
时,您实际上再次调用了setter,从而一遍又一遍地重复,直到达到最大深度递归限制。当您设置
self._price
时,您没有使用 setter,而是进行常规分配。

© www.soinside.com 2019 - 2024. All rights reserved.