Expert Python Programming(Third Edition)
上QQ阅读APP看书,第一时间看更新

As a function

There are many ways to write custom decorators, but the simplest way is to write a function that returns a sub-function that wraps the original function call.

The generic patterns is as follows:

def mydecorator(function): 
    def wrapped(*args, **kwargs):      
        # do some stuff before the original 
        # function gets called 
        result = function(*args, **kwargs) 
        # do some stuff after function call and 
        # return the result 
        return result 
    # return wrapper as a decorated function 
    return wrapped