Record python The function of ornaments , Often forget this , I can't recall , It must be because you use less .
Let's start with a simple decorator example
from functools import wraps
def other_fun(func):
print(" Start execution other_fun")
@wraps(func)
def warrp():
print(" Start execution warrp")
func()
print(" After execution warrp")
return warrp
@other_fun
def myfun():
print("myfun")
myfun()
Print the results :
Start execution other_fun
Start execution warrp
myfun
After execution warrp
A simple decorator is equivalent to a function myfun() It is said that other_fun() perform
myfun = other_fun(myfun)
We can think of a closure as a special function , This function consists of two nested functions ,
They are called external functions and internal functions , The return value of an outer function is a reference to an inner function , So that's the closure .
The second example above , Parameter decorator
# Do not use decorators
def other_fun(func):
print(" Start execution other_fun")
def warrp(num):
print(" Start execution warrp")
result = func(num)
print(" After execution warrp")
return print(result)
return warrp
def myfun(num):
print("myfun")
return num
test = other_fun(myfun)
test(101)
Start execution other_fun
Start execution warrp
myfun
After execution warrp
101
We have seen an example of closures and function arguments , So the decorator
It's actually a closure + Function arguments , If you understand the above example , Now you just need to change the code format a little , It becomes a decorator
The syntax is more concise and beautiful when executed
# Use decorators
def other_fun(func):
print(" Start execution other_fun")
@wraps(func)
def warrp(*args):
print(" Start execution warrp")
result = func(*args)
print(" After execution warrp")
return print(result ) #result = 101
return warrp
@other_fun
def myfun(num):
print("myfun")
return num
myfun(101)
Start execution other_fun
Start execution warrp
myfun
After execution warrp
101
By introducing functools Methods wraps, Ensure the primitive and integrity of the original function
@wraps Accept a function , Decorate , And added the copy function name 、 Annotation document 、 Parameter list and other functions , In this way, we can access the properties of the function before decoration in the decorator
Application of decorator , logging
... To be continued