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 lessonRead 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
- Create a Read-Only Name PropertyBeginner
- Add Age Validation with a SetterIntermediate
- Fix the Infinite RecursionIntermediate
- Build a Computed Full NameIntermediate
- Refactor to Use @propertyAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz