1. The role of decorator
In no way alter the function call based on before and after the function to add functionality .
2. syntactic sugar
Position is placed above the decorative function
DEF Timer (F): # decorator function DEF Inner (): Start = the time.time () F () # decorated function End = the time.time () Print (End - Start) return Inner @timer # syntactic sugar : @ decorator function name DEF FUNC (): the time.sleep ( 0.1 ) Print ( ' 111 ' ) # action syntactic sugar corresponds executed here: func = timer (func), i.e. the inner assign FUNC Fun ( )
3. The decorated function return value
DEF Timer (F): DEF Inner (): Start = the time.time () RET = F () # decorated function End = the time.time () Print (End - Start) return RET return Inner @timer # syntactic sugar : @ decorator function name DEF FUNC (): the time.sleep ( 0.1 ) Print ( ' 111 ' ) return '222 ' # add a return value # syntactic sugar acts as performed here: FUNC = Timer (FUNC) RET =Fun () print (right)
Function with parameters to be decorated 4
In the position of all parameters need to add parameters to join
DEF Timer (F): DEF Inner (* args, ** kwargs): # universal parameter Start = the time.time () RET = F (* args, ** kwargs) # decorated function End = the time.time ( ) Print (End - Start) return RET return Inner @timer # syntactic sugar: @ decorator function name DEF FUNC (A, B): the time.sleep ( 0.1 ) Print ( ' 111 ' , A) return '222' # Add The return value #Syntactic sugar equivalent action executed here: FUNC = Timer (FUNC) RET = Fun (. 1, B = 2 ) Print (RET)
The decorative pattern fixed
6.functiools.wraps()
Role: do not change the function of decorative properties.
7. may change at any time whether the decorator
@timmer_out (flake):
1. First perform the function timmer_out (FLAGE)
2. The implementation of the results to the @, that @timmer
The multi-function of a decorative decorator
After you perform @ wrapper1 the results to the @wrapper execution.