Editor

Build a Simple 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 lesson

Create a descriptor class called Positive that only allows positive numbers to be set. If someone tries to set a non-positive value, raise a ValueError with the message '{name} must be positive'.

Use it in a Rectangle class with width and height attributes. Create a Rectangle, set width=5 and height=3, then print both values.

class Positive:
# Your descriptor code here
pass
class Rectangle:
width = Positive('width')
height = Positive('height')
# Create rectangle, set width=5, height=3, print both

More Descriptor exercises

All Python exercises · 50 practice problems · Metaprogramming quiz