Classes as decorators
In section Function as decorators in Chapter 7, Functions , we saw how functions can be modified by applying another function as a decorator. In previous examples, we saw how classes can be made to behave as functions as long as they are provided with the __call__
method. We will use this here to show how classes can be used as decorators.
Let us 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...