Editor

Fix the Infinite Recursion

Intermediate · Fix the bug · from Python @property: Getters, Setters, and Computed Attributes

From the lesson: Python @property: Getters, Setters, and Computed Attributes

Imagine a thermostat on your wall. You set the temperature to 72°F and the system heats your house. But what if someone sets it to 5000°F? The house wouldn't literally reach that temperature, but your heating system would run forever trying. A smart thermostat would reject that value immediately.

Read the lesson

This class causes infinite recursion when you create an instance. Find and fix the bug so that creating Product('Widget', 9.99) prints the price correctly.

class Product:
def __init__(self, name, price):
self.name = name
self.price = price
@property
def price(self):
return self.price # Bug is here
@price.setter
def price(self, value):
if value < 0:
raise ValueError('Price cannot be negative')
self.price = value # Bug is here too
p = Product('Widget', 9.99)
print(p.price)

More @property exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz