Python Descriptor Classes: Hook into Attribute Access
Published in
1 min readFeb 8, 2019
Python allows us to execute code when an attribute of our class gets accessed, set, or removed through Descriptor Classes. A descriptor class is just a simple class that defines either __get__
, __set__
or __delete__
methods. For example:
class MyDescriptor(object):
def __init__(self, *args, **kwargs):
self.value = 1
def __get__(self, obj, owner=None):
print('get is called')
try:
return self.value
except AttributeError:
# do something
raise AttributeError
def __set__(self, obj, value):
print('set is called')
self.value = value
def __delete__(self, obj):
print('delete is called')
del self.value
To use the descriptor class, you need to make an instance of it an attribute of your class like:
class Foo(object):
bar = MyDescriptor()
Now every time the bar
attribute of the instances of your class Foo
is accessed, set, or deleted the corresponding function you defined in MyDescriptor
is executed.
>>> a = Foo()
>>> print(a.bar)
get is called
1
>> a.bar = 2
set is called
>> print(a.bar)
get is called
2
>> del a.bar
delete is called
Descriptor classes are simple yet very powerful. Use it.
Thanks for reading.