Descriptors are an amazing tool to have in our toolbox, as they come in handy in many opportunities.
Probably the best thing about descriptors, is that they can improve other solutions. Let's see how we can write better decorators, by using descriptors.
Decorate a class method
Imagine we have a very simple decorator, that does nothing but returning a text, with what the original function returns:
class decorator:
def __init__(self, func):
self.func = func
wraps(func)(self)
def __call__(self, *args, **kwargs):
result = self.func(*args, **kwargs)
return f"decorated {result}"
class Object:
@decorator
@classmethod
def class_method(cls):
return 'class method'
If we apply the decorator to a simple function, it'll work, as expected. However, when it's applied to a class method, we can see an error: