Reference:
Http://www.wklken.me/posts/2013/07/19/python-translate-decorator.html
Http://www.cnblogs.com/wupeiqi/articles/4980620.html
First, the necessary knowledge of the adorner
1, function can be assigned to a variable
defShow (msg):Print(msg)#call the show functionShow"This is the output of call show ()")#assign a function show to FooFoo =Show#call FooFoo"This is the output that calls Foo ()")#call F2 again after deleting the F1 functiondelShowfoo ("This is the output of the bar with Foo () after the show () is removed")########## #输出结果This is the output of call show () which is the output of the call Foo () which is the output of the Delete show () after the bar with Foo ()
2. Functions can be redefined
def Show (): Print (" first definition show") def Show (): Print (" second definition show") # the output of the function will be: Second definition showshow ()
3, function of function body inside can also define function, and in function body inside can be called immediately
def Show (): def foo (): return " Wenchong " Print (foo ())
4. The return result of a function can also be a function
defRun (action='Remove'): defRemove_user ():return "del user name" defAdd_user ():return "Add user name" ifAction = ='Remove': returnRemove_userElse: returnAdd_user#assigns the return value of the run () function to the actionAction = run (action='Add')#the value of the output action is a function objectPrint(Action)#adding () After the action will output the return value of the Add_user () functionPrint(Action ())#You can also output this directlyPrint(Run (action='Add')())###### #输出结果<function Run.<locals>.add_user at 0x10ce16840>Add user nameadd user name
5, functions can also be passed as a parameter to the function
def Show (): return " Wenchong " def foo (func): = func () print(msg)# passes the function show as a variable to the Foo function foo ( Show)###### #输出结果Wenchong
6. Dynamic Parameters
def my_func (*args,**Kwargs): print(Args,kwargs)
Second, write an adorner
An adorner is a function that takes another function as a parameter
deffunc_action (my_func):#define a Inner_func function that the user executes before and after the My_func function executes other code defInner_func ():Print("my_func start ...") #Call the My_func function, remember that there must be ()My_func ()Print("My_func End ...") #returns the Inner_func function, which contains the code for the My_func function and the code before and after My_func returnInner_func#Create a functiondefMy_func ():Print("The my_func function is called")#Call the My_func functionMy_func ()## # # #输出结果The my_func function is called
The Func_aciton function can pass a function as a parameter and add code before and after this parameter
Then you can pass the My_func function to Func_aciton to finish decorating the my_func.
# Assign func_action to a variable other_my_funcother_my_func = func_action (my_func)# call Other_my_ The Func function other_my_func ()### # # # # # # # # # # # # # #输出结果 my_func start...my_func
This way, each time you want to add code to and from a function, you can re-assign it to another variable by Func_aciton and execute it.
Third, the use of decorative device
Using the adorner in the example above is too cumbersome to define another variable, and then call this variable, Python provides a special syntax to use @func_action add adorners on top of the function
@func_action def My_func (): Print ("my_func function is called ") # Call the My_func function My_func () # # # #输出结果 My_func start...my_func function is called My_func end ...
The function of the @ symbol:
1. Pass the function below the @ symbol as a parameter to the function following the @ sign, and execute
2. Re-assign the returned result to the function below the @ symbol
Iv. passing parameters to the adorner function and getting the return value
When the decorated function has parameters, it is possible to pass parameters to the decorated parameters by means of dynamic parameters.
When the decorated function has a return value, it can be returned via Inner_func by capturing the return value of func
defFunc_action (func):#passing parameters to a function that is not decorated defInner_func (*args,**Kwargs):Print("func-Start ...") #gets the return value of the decorated functionret = func (*args,**Kwargs)Print("func End ...") #returns the returned value of the decorated function to Inner_func returnretreturnInner_funcV. Passing parameters to the adorner
An adorner is a function that functions as a parameter, so if you need to pass parameters to the adorner, you need to declare a function to create the adornment
#declaring functions that create adornersdefDecorator_maker (MSG1,MSG2):Print("decorator start make ...", MSG1)#the real decorator defMy_decorator (func):defInner (*args,**Kwargs):Print('func run start ...') ret= Func (*args,**Kwargs)Print('func Run end ...') returnretreturnInnerPrint("decorator End make ...", MSG2)returnMy_decorator@decorator_maker ('Wen','Chong')defShow (msg):Print(msg)returnmsg#call a function that has been decoratedShow'AAAA')
Output Result:
Decorator start make ... Wendecorator End Make ... Chongfunc run Start...aaaafunc Run end ...
An adorner code fragment that can handle any parameter
#a decorative decorator (a good round ...)defDecorator_with_args (decorator_to_enhance):"""This function will be used as an adorner it must decorate another function it will allow any adorner to receive any number of parameters to facilitate your query every time how to implement""" #same technique for passing parameters defDecorator_maker (*args, * *Kwargs):#create an adorner that only receives functions #But here are the arguments that were passed from the creator . defDecorator_wrapper (func):#we return the result of the original adorner #This is a normal function, and the return value is another function #traps: adorners must have this special signature, otherwise it will not take effect returnDecorator_to_enhance (func, *args, * *Kwargs)returnDecorator_wrapperreturnDecorator_maker
Python Learning-Decorators