Part 4 · Section 08

Descriptors

A property is great for one attribute, but what if ten attributes across five classes all need the same validation? Writing ten nearly identical getter/setter pairs is exactly the kind of repetition Python lets you avoid. The tool for this is the descriptor: an object, stored as a class attribute, that takes over what happens when you read, write or delete that attribute on an instance.

Descriptors are not an exotic add-on. property, classmethod, staticmethod, __slots__ members, and even plain functions turning into bound methods all work through the same descriptor protocol. Once you understand it, a lot of “magic” in Python becomes ordinary code you could write yourself.

In this section you’ll learn:

Lectures

  1. 01Descriptors✓
  2. 02Getters and Setters✓
  3. 03Using as Instance Properties✓
  4. 04Strong and Weak References✓
  5. 05Back to Instance Properties✓
  6. 06The __set_name__ Method✓
  7. 07Property Lookup Resolution✓
  8. 08Properties and Descriptors✓
  9. 09Application - Example 1✓
  10. 10Application - Example 2✓
  11. 11Functions and Descriptors✓

Practice: quiz & exercises

12 quiz questions · 4 coding exercises

Go to practice →