First, what is an adorner
The adorner is a well-known design pattern, which is often used in scenes where there is a demand for facets, with the classic insert log, performance test, transaction processing, and so on. Decorators are a great design for solving such problems, and with adorners, we can pull out a lot of the same code that is not relevant to the function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object. Simply put, the Python decorator can be viewed as a function of a wrapper function without rigor.
For example, there is a function:
1 def func (): 2 Print ' func () run. ' 3 4 if ' __main__ ' __name__ : 5 func ()6 outputs after run:7 func () run
Now you need to print a log before and after the function runs, but you do not want or have permission to modify the structure inside the function, you can use the adorner:
1 deflog (function):2 defWrapper (*args, * *Kwargs):3 Print 'before function [%s ()] run.'% function.__name__4rst = function (*args, * *Kwargs)5 Print 'After function [%s ()] run.'% function.__name__6 returnrst7 returnwrapper8 9 @logTen deffunc (): One Print 'func () run.' A - if '__main__'==__name__: -Func ()
For the original function "func ()" is not modified, but to use the adorner log, the output after the run:
1 before function [func ()] run. 2 func () run. 3 After function [func ()] run. 4 Place the "@log" into the func () function definition, equivalent to executing the following statement:5 func = log ( Func
Because log () returns a function, the original Func points to the function wrapper returned by log (). The wrapper parameter list is (*args, **kwargs), so it can accept all parameter calls, and in wrapper, one line is printed first
' Before function [%s ()] run. '% function.__name__, then executes the original function and records the return value, in the output
' After function [%s ()] run. '% function.__name__, which returns the execution result of the function.
Here's an example:
1 defLog (text="'):2 defDecorator (function):3 @functools. Wraps (function)4 defWrapper (*args, * *Kwargs):5 Print 'before function [%s ()] Run, text: [%s].'% (function.__name__, text)6rst = function (*args, * *Kwargs)7 Print 'After function [%s ()] Run, text: [%s].'% (function.__name__, text)8 returnrst9 returnwrapperTen returnDecorator One A@log ('Log Text') - deffunc (): - Print 'func () run.' the - if '__main__'==__name__: -Func ()
View Code
The output is as follows:
1 before function [func ()] Run, text: [log text]. 2 func () run. 3 after function [func ()] Run, text: [Log text].
adorners in Python