psj01
psj01

Reputation: 3245

Getting a RecursionError in a python class

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...

Upvotes: 0

Views: 746

Answers (2)

Prune
Prune

Reputation: 77850

    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

Upvotes: 1

adrtam
adrtam

Reputation: 7221

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 (i.e., more conventional) way is to use self._price to hold your value.

Upvotes: 5

Related Questions