I have a Product class defined in Python as below:
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
When I try to set the price attribute of a new instance of Product (prod):
prod = Product()
prod.price = 25
print(prod.price)
I get an error saying:
RecursionError: maximum recursion depth exceeded
Can someone please explain what I'm doing wrong here...
Recursion occurs here:
@price.setter
def price(self, value):
self.price = value
which self.price =
will trigger the same price()
function as you make it a setter. The better (ie, more conventional) way is to use self._price
to hold your value.
self.price = value
This is a recursive reference to the setter itself. Look up how to write a setter; you'll see the problem. You need to refer to the pseudo-private variable:
self._price = value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.