Refactor to Use @property
Advanced · Refactor · 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 lessonRefactor this class to use @property instead of explicit getter/setter methods. The get_speed and set_speed methods should be replaced with a speed property. Keep the validation logic. Then create a Car(60), print speed, set it to 100, and print again.
class Car:
def __init__(self, speed):
self.set_speed(speed)
def get_speed(self):
return self._speed
def set_speed(self, value):
if value < 0:
raise ValueError('Speed cannot be negative')
if value > 200:
raise ValueError('Speed too high')
self._speed = value
# Refactor the class above, then:
# Create Car(60), print speed, set to 100, print again
More @property exercises
- Create a Read-Only Name PropertyBeginner
- Add Age Validation with a SetterIntermediate
- Fix the Infinite RecursionIntermediate
- Build a Computed Full NameIntermediate
- Predict the Temperature OutputIntermediate
All Python exercises · 50 practice problems · Object-Oriented Programming quiz