Implement Managed Attributes with Descriptors
Core idea
A descriptor is an object stored on a class whose type defines an attribute hook such as get, set or delete. Python invokes these hooks during normal attribute access. In get(self, instance, owner), instance is None for class access; return self there when callers need the descriptor itself. Store per-instance values on the managed instance, not on the shared descriptor.
class Label: def __get__(self, instance, owner): if instance is None: return self return instance.code.upper()class Parcel: label = Label() def __init__(self, code): self.code = codeprint(Parcel('ax').label)print(isinstance(Parcel.label, Label))The instance supplies the data; class access returns the descriptor.
Validate a quantity
class Quantity: def __get__(self, instance, owner): if instance is None: return self return instance._quantity def __set__(self, instance, value): if value < 0: raise ValueError('negative quantity') instance._quantity = valueclass Stock: quantity = Quantity()a, b = Stock(), Stock()a.quantity = 3b.quantity = 8try: a.quantity = -1except ValueError: print(a.quantity, b.quantity)The setter rejects the update before changing storage. Each instance retains its own quantity.
Common mistake
Do not store the quantity in self.value inside the descriptor: all instances would share it. A descriptor assigned only to an instance does not participate in this automatic class lookup.
Practice
Adapt Quantity to reject values above 100. Create two instances, change one and verify that the other is unaffected.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Descriptor protocol
Check your understanding of descriptor protocol.
What is printed?
class D: def __get__(self, obj, owner): return 12class C: x=D()print(C().x)What is printed?
class D: def __get__(self, obj, owner): return obj is Noneclass C: x=D()print(C.x, C().x)Where should distinct instance values live?
Which hook intercepts assignment?