When executing the function* break up
When defining a function* aggregate
from functools import wraps
def wrapper(f): # f = func1
@wraps(f)
def inner(*args,**kwargs): #Aggregate
#args (1,2,3)
'''Relevant operations before executing the function'''
ret = f(*args,**kwargs) # break up 1,2,3
'''Relevant operations after executing the function'''
return right
return inner
# When the function is executed, * is scattered.
# When the function is defined, *aggregate.
@wrapper # func1 = wrapper(func1) func1 = inner
def func1(*args): #args (1,2,3)
print(666)
return args
print(func1(*[1,2,3])) # inner(1,3,5) Disperse
useful information of print function
@wrapper def
func1(): " "
" This
function is the function to complete the login, the parameters are... func1() print(func1.__name__) print(func1.__doc__)
#666
func1
This function is the function of completing the login, and the parameters are ... functions.
: return: The return value is whether the login is successful or not (True, False)
Decorator with parameters
import time
def timmer(*args,**kwargs):
def wrapper(f):
def inner(*args,**kwargs):
if flag:
start_time = time.time()
ret = f(*args,**kwargs)
time.sleep(0.3)
end_time = time.time()
print('此函数的执行效率%f' % (end_time-start_time))
else:
ret = f(*args, **kwargs)
return ret
return inner
return wrapper
flag = False
@timmer(flag,2,3) # 两步:1,timmer(flag) --> wrapper 2,@wrapper 装饰器
def func1():
print(666)
@timmer(flag)
def func2():
print(777)
func1()
func2()
多个装饰器装饰一个函数
def wrapper1(func): f = func
def inner1():
print('wrapper1 ,before func')
func()
print('wrapper1 ,after func')
return inner1
def wrapper2(func): func = inner1
def inner2():
print('wrapper2 ,before func')
func()
print('wrapper2 ,after func')
return inner2
@wrapper2 然后读@wrapper2 f = inner2
@wrapper1 先读@wrapp1 f = inner1
def f():
print('in f')
f() 再读f()