Python3 ornament and python3 Ornament
Python3 decorator 1. Closure
The closure has two conditions: the function contains an inner function, and the inner function references the variable defined by the outer function.
Eg:
Def outer ():
X = 10
Def inner ():
Print (x)
Return inner
2. decorator
The modifier is used to add functions without changing the source code of the original function. Execution Process: when calling a function modified by the decorator, the decorator is called first, passing the function name of the decorator function into the decorator function, and executing the inner function of the decorator, the inner function calls the decorated function to execute the decorated function. The added function is written in the inner function, so the added function is also implemented. The advantage of doing so is that the call method of the function to be decorated remains the same, so as to prevent the phenomenon of moving the whole body; the source code of the function to be decorated is not changed, in line with the open and closed principle.
Note that the decorator function must be a closure function.
Eg:
Decorator functions:
ImportTime
DefShow_time (f ):
DefInner (* args, ** kwargs): # sets the variable length parameter to prevent the decoration function from having parameters.
Start_time = time. time ()
F (* args, ** kwargs)
Time. sleep (3)
End_time = time. time ()
Print ('End _ time = % s'% (End_time-start_time ))
ReturnInner ()
@ Show_time
DefFoo (): # function modified by the decorator
Print ('OK')
Foo () # Call a function
If you want to transmit parameters to the decorator function, an external function is added to the periphery of the decorator function.
Eg2:
Def outer (* args ):
Def show_time (f ):
Def inner (* args, ** kwargs ):
Pass
Return inner
Return show_time
@ Outer ('parameter ')
Def foo ():
Pass
Foo () # Call a function