Command Palette

Search for a command to run...

Hectal
Phase 13: Python Internals and Performance
Python · Exercise 3 of 6 PreviousNext
Advanced

A descriptor that validates

Write a data descriptor Ranged(low, high) that only accepts numbers from low to high (both allowed). Assigning a number outside the range must raise ValueError.

Use __set_name__ so one descriptor class can serve many attributes, and keep each instance's value on the instance, not on the descriptor. Reading it through the class must return the descriptor.

Then use it in Thermostat as target = Ranged(5, 30). The constructor Thermostat(target) must validate through the descriptor too.

What Check tests

  1. A valid value is stored and read back
  2. A value outside the range raises ValueError
  3. A rejected value does not change the old one
  4. The constructor validates too
  5. Two instances keep separate values
  6. Reading on the class returns the descriptor
  7. It works under another attribute name

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.