Build a Range-Validated Descriptor
Advanced · Write the code · from Python Descriptors: The Secret Behind @property and ORM Fields
From the lesson: Python Descriptors: The Secret Behind @property and ORM Fields
When you use @property in Python, something interesting happens behind the scenes. The attribute doesn't just sit there waiting to be read - it intercepts access and runs custom code. How does that work?
Read the lessonCreate a descriptor InRange that accepts min_val and max_val parameters and ensures the value stays within that range. Raise ValueError with '{name} must be between {min} and {max}' for out-of-range values.
Use it in a GameCharacter class:
health = InRange(0, 100)level = InRange(1, 99)Create a character, set health=75 and level=10, then print both.
class InRange:
# Your code here
pass
class GameCharacter:
health = InRange(0, 100)
level = InRange(1, 99)
# Create character, set values, print them
More Descriptor exercises
- Build a Simple DescriptorAdvanced
- Predict the Descriptor OutputAdvanced
- Build a TypeChecked Descriptor with __set_name__Advanced
- Fix the Shared State BugAdvanced
- Build a Cached Property DescriptorAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz