The decorator can add some extra functions before and after the target function execution without modifying the target function code.
For example, there is a simple function
Import time
Def func1 ():
Print ("This is a simple function")
Time.sleep (2)
To add a calculation time function to this function, you can use the decorator
Let the function use a decorator, that is, add the @ function name above the definition of the function, as below, which is equivalent to writing func1=outer (FUNC1) to the program behind it
The reason why a parameter outside the function is used in a function is a closed packet
Import time
def outer (f): def inner (): start = Time.time () f () end = Time.time () print (End-start) return Inner@outer#func1=outer (FUNC1) def func1 (): print ("This is a simple function") Time.sleep (2) func1 ()
#输出
This is a simple function.
2.000551223754883
If a function with parameters needs to be modified,
def outer (f): def inner (x, y): start = Time.time () f (x, y) end = Time.time () print (End-start) Return Inner@outer#func1=outer (FUNC1) def add (x, y): print (x+y) Time.sleep (2) Add
If you want to add some other statements in the decorator, such as a judgment statement, to control whether certain features are used
Import timedef judge (Flag=true): def outer (f): def inner (x, y): start = Time.time () f (x, y) end = Time.time () print (End-start) return inner if flag==true: print ("This is a feature") return Outer@judge () #judge () is actually equivalent to outer, except that you can add the parameter def add (x, y): print (x+y) Time.sleep (2) Add
Python Basic Learning----Decorator