Member-only story
A Python descriptor
2 min readApr 4, 2024
A Python descriptor is an object attribute with “binding behavior,” meaning its attribute access has been overridden by methods in the descriptor protocol. These methods are __get__
, __set__
, and __delete__
. If any of these methods are defined for an object, it can be considered a descriptor. Descriptors are used to manage the attributes of different classes using the same code or to create attributes that can only be accessed through special methods.
Example: Creating and Using a Descriptor
Let’s create a simple descriptor that sets and gets a value, ensuring the value is always an integer.
class IntegerDescriptor:
def __init__(self):
self.value = 0
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
if not isinstance(value, int):
raise TypeError("Value must be an integer")
self.value = value
class MyClass:
number = IntegerDescriptor()
# Using the descriptor
my_instance = MyClass()
my_instance.number = 10 # Works fine
print(my_instance.number) # Output: 10
try:
my_instance.number = "Hello" # Raises TypeError
except TypeError as e:
print(e) # Output: Value must be an integer
In this example:
IntegerDescriptor
defines__get__
and__set__
methods to control access to the…