Descriptors: __get__, __set__, __delete__
Implement the descriptor protocol for attribute access control.
What Is a Descriptor?
A descriptor is an object that defines __get__, __set__, or __delete__ and is assigned as a class attribute. Python calls these methods on attribute access.
class Descriptor:
def __get__(self, obj, objtype=None):
print(f"__get__ called, obj={obj}")
return 42
class MyClass:
attr = Descriptor()
print(MyClass().attr) # __get__ called ... 42Data vs Non-Data Descriptors
Data descriptors define __set__ or __delete__ and take precedence over the instance __dict__. Non-data descriptors (only __get__) yield to __dict__.
class DataDesc:
def __get__(self, obj, t): return "data"
def __set__(self, obj, val): pass
class NonDataDesc:
def __get__(self, obj, t): return "nondata"
class C:
d = DataDesc()
n = NonDataDesc()
c = C()
c.__dict__["n"] = "instance" # shadows the non-data desc
c.__dict__["d"] = "instance" # does NOT shadow data desc
print(c.n) # instance
print(c.d) # dataAll lessons in this course
- How Python Classes Are Created
- Writing Custom Metaclasses
- Descriptors: __get__, __set__, __delete__
- __slots__ and Memory Optimization