0

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

2
  • You are trying to get/set a property value by getting/setting the property which in turn tries to get/set the property value by getting/setting the property which in turn... Commented May 15, 2019 at 19:05
  • 1
    Your getter and setter calls themselves recursively: return self.price self.price = value Commented May 15, 2019 at 19:05

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I understand the problem now.
1
    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

1 Comment

Thanks. make sense to me now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.