上QQ阅读APP看书,第一时间看更新
As a class
While decorators can almost always be implemented using functions, there are some situations when using user-defined classes is a better option. This is often true when the decorator needs complex parameterization, or if it depends on a specific state.
The generic pattern for a non-parameterized decorator defined as a class is as follows:
class DecoratorAsClass: def __init__(self, function): self.function = function def __call__(self, *args, **kwargs): # do some stuff before the original # function gets called result = self.function(*args, **kwargs) # do some stuff after function call and # return the result return result