Simple descriptor
suggest changeThere are two different types of descriptors. Data descriptors define __set__() or __delete__(). Non-data descriptors define __get__() and neither of those two methods. This distinction is important when considering overrides and the namespace of an instance’s dictionary. If a data descriptor and an entry in an instance’s dictionary share the same name, the data descriptor will take precedence. However, if instead a non-data descriptor and an entry in an instance’s dictionary share the same name, the instance dictionary’s entry will take precedence.
To make a read-only data descriptor, define both __get__() and __set__(), with __set__() raising an AttributeError when called. Defining __set__() with an exception-raising placeholder is enough to make it a data descriptor.
descr.__get__(self, obj, type=None) --> value
descr.__set__(self, obj, value) --> None
descr.__delete__(self, obj) --> None
An implemented example:
class DescPrinter(object):
"""A data descriptor that logs activity."""
_val = 7
def __get__(self, obj, objtype=None):
print('Getting ...')
return self._val
def __set__(self, obj, val):
print('Setting', val)
self._val = val
def __delete__(self, obj):
print('Deleting ...')
del self._val
class Foo():
x = DescPrinter()
i = Foo()
i.x
# Getting ...
# 7
i.x = 100
# Setting 100
i.x
# Getting ...
# 100
del i.x
# Deleting ...
i.x
# Getting ...
# 7
After del i.x, __get__ returns 7 again because _val = 7 lives on the class. __set__ stored 100 on the descriptor instance, and __delete__ removes only that instance value. This output was checked on Python 3.14.6.