In Python, if any of the methods __get__, __set__, and __delete__ is defined for an object, then this object is said to be a descriptor. Descriptors are the mechanism behind properties, methods, static methods, class methods, and super().
Note that descriptors are only invoked for new style objects or classe (inherits from object).
So, define any of these methods
d.__get__(self, obj, type=None) --> value
d.__set__(self, obj, value) --> None
d.__delete__(self, obj) --> None
and an object is considered a descriptor and can override default behavior (when invoking attribute).
The mechanism of invoking attributes is complex and differs between a class and an object. It is out of scope here, but you should be aware of these differences.
Finally, note this terminology:
- If an object defines both __get__ and __set__, it is a data descriptor
- If an object only defines __get__, it is a non-data descriptor.
Example
class Data(object):
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
return self.val
def __set__(self, obj, val):
self.val = val
x = Data(10, 'var "x"')
x.var = 5
References: users.rcn.com