0Pricing
Python Academy · Lesson

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 ... 42

Data 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)   # data

All lessons in this course

  1. How Python Classes Are Created
  2. Writing Custom Metaclasses
  3. Descriptors: __get__, __set__, __delete__
  4. __slots__ and Memory Optimization
← Back to Python Academy