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 ...

Get Scientific Computing with Python 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.