Skip to content
dreamcode
dreamcode
Map
Validation Descriptor
Section challenge · AdvancedPython
Reward: +70 XP
PROBLEM

Validation Descriptor

Write a descriptor class IntegerRange that restricts a class attribute to integers between a minimum and maximum value (inclusive). The __init__(self, min_val, max_val) constructor should accept min_val and max_val. If __set__(self, instance, value) is called with a value that is not an integer, or is outside the specified range, raise a ValueError.

Also write a class Planet that uses the descriptor for its gravity attribute:

class Planet:
    gravity = IntegerRange(1, 100)
    def __init__(self, name, gravity):
        self.name = name
        self.gravity = gravity

Finally, write a helper function test_descriptor(name, gravity) that instantiates Planet(name, gravity). If it succeeds, return the string '{name} is at {gravity}g'. If a ValueError is raised, catch it and return 'invalid gravity'.

Examples
test_descriptor('Mars', 38)
'Mars is at 38g'
test_descriptor('Jupiter', 150)
'invalid gravity'
solution.py
PYTHON
Saved as you type

Tests

0 of 4 passing
  • Mars 38g → Mars is at 38g
    test_descriptor('Mars', 38)
    expected 'Mars is at 38g'
  • Jupiter 150g → invalid gravity
    test_descriptor('Jupiter', 150)
    expected 'invalid gravity'
  • Pluto 0g → invalid gravity
    test_descriptor('Pluto', 0)
    expected 'invalid gravity'
  • Earth string input → invalid gravity
    test_descriptor('Earth', 'normal')
    expected 'invalid gravity'
On the line
+70 XP
Pass all 4 tests to claim it.