The last time NH asked me the question of the decorator, at that time to learn the dishes, and now also very dishes, just abruptly their memories and examples to help her answer.
This time I have learned again:
The adorner performs the relevant functions before and after the function:
Both the adorner and the function do not contain parameters, and to return the intrinsic function, you need to save the return value of the intrinsic function to a variable and return the value.
def deco (func):
Print ("before")
ret = func ()
Print ("End")
return ret
Def myfunc ():
Print ("Hello")
return "Hello"
z = Deco (myfunc)
Before
Hello
End
Z
' Hello '
Use @ To decorate
function as an example, except that the function definition MyFunc
@deco
Def myfunc ():
Print ("Hello") return "Hello"You'll notice that when the function is defined, the Deco decorator executes and calls MyFunc () again,
>>> MyFunc ()
Traceback (most recent):
File "", Line 1, in
TypeError: ' str ' object is not callable
Cannot execute, you can call MyFunc, you can see the return value, but the role of the adorner is not, this is not what we want AH
Use closures (inline functions) to ensure that each time the function is executed, the adorner's function guarantees
overriding adorner functions
def deco (func):
Def _deco ():
Print ("before") ret = func () print ("End") return RETReturn _deco
@deco
Def myfunc ():
Print ("Hello") return "Hello"
z = MyFunc ()
This time, when the function is defined, the function is not executed, using z= myfunc (), the function executes, and returns the return value to Z, this time the parameter of the adorner function is the function we want to function, the inner closure has no parameters
Adorners decorate functions that have parameters,
The parameter of the adorner is our function, and the parameter of the inside closure is the parameter of the function # The mathematical expression is this way drop F = Deco (func) (*kwargs),
def deco (func):
Def _deco (A, b): print ("before") ret = func (A, b) print ("End") return Retreturn _deco@deco ():
def add (A, B)
Print ("add called") return A+b
Add (+)
- adorners own parameters, functions have no parameters
The parameters of the adorner are its own parameters, and the parameters of the first closure function are our functions.
def deco (ARG):
def _deco (func):Def __deco (): Print (" before") print ("Deco args is %s"% (ARG)) ret = func () print ("End") return ret return __decoReturn _deco
@deco ("Lambda")
Def myfunc ():
Print ("Hello") return "Hello"
- The parameters of the function are indeterminate, and the parameters of the adorner are indeterminate.
Parameters (args, *kwargs), auto-adaptive variable parameter and named parameters "
Reference: http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
Python Decorator Learning, (Basics)