First, the adorner definition
A way to dynamically add functionality during code runs, called an "adorner" (Decorator). Essentially, decorator is a higher-order function that returns a function.
1>>>deflog (func):2...defWrapper (*args, * *kw):3...Print('Call %s:'% func.__name__)4...returnFunc (*args, * *kw)5...returnwrapper6 ... 7>>>@log8...defNow ():9...Print('2017-12-16')Ten ... One>>>Now () A Call now : -2017-12-16 ->>>
Observe the above log
, because it is a decorator, so accept a function as an argument and return a function. To use Python's @ syntax , place the decorator at the definition of the function.
Put @log
to now()
the definition of the function, the equivalent of executing a statement:
1 >>>now = log (now)
Second, with the parameter of the adorner
1>>>deflog (text):2...defDecorator (func):3...defWrapper (*args, * *kw):4...Print('%s%s:'% (text, func.)__name__))5...returnFunc (*args, * *kw)6...returnwrapper7...returnDecorator8 ... 9>>> @log ('Execute')Ten...defNow (): One...Print('2017-12-16') A ... ->>>Now () - Execute Now: the2017-12-16
Compared to the two-layer nested decorator, the 3-layer nesting effect is this:
1 >>> now = log ('execute') (now)
Third, Functools.wraps
There is no problem with the definitions of the two decorator, but the last step is not the case. Because we're talking about functions and objects, and it has __name__
properties like that, but you see the functions after the decorator decoration, and they __name__
have changed from the original ‘now‘
‘wrapper‘
:
1 >>> now. __name__ 2 ' wrapper '
Because the name of the function returned is the same, wrapper()
‘wrapper‘
so you need to copy the properties of the original function __name__
into the wrapper()
function, otherwise, some code that relies on the function signature will be executed with an error.
There is no need to write wrapper.__name__ = func.__name__
such code, Python functools.wraps
is built to do this, so a complete decorator is written as follows:
1 ImportFunctools2 3 deflog (func):4 @functools. Wraps (func)5 defWrapper (*args, * *kw):6 Print('Call %s ():'% func.__name__)7 returnFunc (*args, * *kw)8 returnWrapper
1 ImportFunctools2 3 deflog (text):4 defDecorator (func):5 @functools. Wraps (func)6 defWrapper (*args, * *kw):7 Print('%s%s ():'% (text, func.)__name__))8 returnFunc (*args, * *kw)9 returnwrapperTen returnDecorator
Python decorator Decorator