Editor

Predict the Temperature Output

Intermediate · Predict the output · 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

Read the code carefully and predict exactly what gets printed. Think about which setter calls succeed and which raise errors.

class Oven:
def __init__(self, temp):
self.temp = temp
@property
def temp(self):
return self._temp
@temp.setter
def temp(self, value):
if value > 500:
raise ValueError('Too hot')
self._temp = value
o = Oven(350)
print(o.temp)
o.temp = 400
print(o.temp)
try:
o.temp = 600
except ValueError as e:
print(e)
print(o.temp)

More @property exercises

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