The Descriptor Protocol: __get__ and __set__
A descriptor is any object defining `__get__`, `__set__`, or `__delete__`. Descriptors power Python properties, methods, `@classmethod`, and ORM model fields 🎛️.
class PositiveInt:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
if instance is None: return self
return instance.__dict__.get(self.name, 0)
def __set__(self, instance, value):
if value < 0: raise ValueError("Must be positive! 🛑")
instance.__dict__[self.name] = value
class Item:
price = PositiveInt()
it = Item()
it.price = 25
print(it.price) # 25 🎛️
# 64. The Descriptor Protocol: __get__ and __set__ A descriptor is any object defining `__get__`, `__set__`, or `__delete__`. Descriptors power Python properties, methods, `@classmethod`, and ORM model fields 🎛️. ```python class PositiveInt: def __set_name__(self, owner, name): self.name = name def __get__(self, instance, owner): if instance is None: return self return instance.__dict__.get(self.name, 0) def __set__(self, instance, value): if value < 0: raise ValueError("Must be positive! 🛑") instance.__dict__[self.name] = value class Item: price = PositiveInt() it = Item() it.price = 25 print(it.price) # 25 🎛️ ``` Descriptors must be assigned as class attributes, not instance attributes. When accessed on instances, Python delegates lookup to the descriptor methods! 🎛️ --- ### Question Where must a descriptor object be bound on a class to work properly? 🧠 - [ ] a. As a class-level attribute on the owning class 🎛️ - [ ] b. Inside `__init__` as an instance attribute - [ ] c. In the global `builtins` dictionary - [ ] d. Inside a local variable inside methods --- ### Challenge Write descriptor `ConstantVal` with `__get__(self, instance, owner)` returning `42`. Bind `val = ConstantVal()` in class `C`. Instantiate `C()` and print `C().val`. 🎯 <details> <summary>Solution</summary> ```python class ConstantVal: def __get__(self, instance, owner): return 42 class C: val = ConstantVal() print(C().val) ``` </details>