In Section 7.8: Function as decorators, we saw how functions can be modified by applying another function as a decorator. In Section 8.1.5: Special methods, we saw how classes can be made to behave as functions as long as they are provided with the method __call__. We will use this here to show how classes can be used as decorators.
Let's assume that we want to change the behavior of some functions in such a way that before the function is invoked, all input parameters are printed. This could be useful for debugging purposes. We take this situation as an example to explain the use of a decorator class:
class echo: text = 'Input parameters of {name}\n'+\ 'Positional parameters {args}\n'+\ 'Keyword parameters {kwargs}\n' def __init__(self, f): self.f = f def __call__(self, *args, **kwargs): print(self.text.format(name = self.f.__name__, args = args, kwargs = kwargs)) ...