我正在尝试构建一个在 setter 装饰器内部进行一些验证的类。我已将代码格式化如下。
class Book():
def __init__(self, price):
self.price = price
@property
def price(self):
return self.price
@price.setter
def price(self, val):
if val >= 50 and val <= 1000:
self.price = val
book4 = Book(200)
print(book4.price)
使用如上所示的我的代码,价格属性开始重复出现,直到达到限制。
我用下划线修改了代码,如下所示,以解决该问题:
class Book():
def __init__(self, price):
self.price = price
@property
def price(self):
return self._price
@price.setter
def price(self, val):
if val >= 50 and val <= 1000:
self._price = val
book4 = Book(200)
print(book4.price)
这给了我另一个错误:
AttributeError: 'Book' object has no attribute '_price'. Did you mean: 'price'?
我的问题是,我想在初始化对象时在setter方法中使用验证,如何才能做到这一点而不导致递归或错误?
你忘记了下划线。
class Book():
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, val):
if val >= 50 and val <= 1000:
self._price = val
book4 = Book(200)
print(book4.price)