Decorator role:
You do not want to modify the function is called, add functionality before and after the function
The simplest decorator:
DEF warpper (F): DEF inner (): Pass F () # execution is decorated function Pass return inner # returns the inner address to to FUNC @wrapper # syntactic sugar @ equal FUNC = warpper (FANC) DEF FUNC (): # decorated function Pass # FUNC = warpper (FANC) FUNC () # perform the function of inner
The order of execution:
When the decorated function returns a value, due to the implementation of that inner, it is necessary to get the decorated function return value of a function in the inner lining, and back out through the inner:
DEF warpper (F): DEF Inner (): Pass RET = F () # receiving the return value of the function to be decorated Pass return RET # returns the return value of the received return Inner @wrapper DEF func (): return None # Return value func ( )
When the decorative function at the same time the need for traditional values, and then only can be received in the inner function, upon receiving the called function also need to be decorated in vivo function, * args and ** kwargs used simultaneously, you may receive parameter types :
def wrapper(f): def inner(*args,**kwargs): pass ret = f(*args,**kwargs) pass return ret return inner @wrapper def func(a,b,c,d = 1): return None func(1,2,3,4)
So, this is a complete decorator, namely fixed pattern decorator
Note:
Syntactic sugar:
Expression: @ decorator function
For example in the code above @wrapper, equivalent to func = wrapper (func) This code