def timer(func): #这里传进来的func就是被扩展的函数
def wrapper():
start = time()
func() #函数执行的地方,即执行sleep(1)
end = time()
print("total execute time of {} is {}".format(func.__name__, end - start))
return wrapper
@timer
def func1():
sleep(1)
@timer
def func2():
sleep(1)
@timer
def func3():
sleep(1)
func1()
func2()
func3()
def judger(t): #传入的t是函数定义时传递的参数,语法糖@那一行的
def wrapper(func):
if t > 5:
print("巨能睡")
else:
print("巨不能睡")
func()
return wrapper
@judger(3)
def func1():
sleep(3)
@judger(6)
def func2():
sleep(6)
#Out:
#巨不能睡
#巨能睡
def adder(func): #这里传进来的func就是被扩展的函数
def wrapper(*args, **kwargs):
total = 0
for item in args:
total += item
print(total)
return wrapper
@adder
def func1(*args, **kwargs):
pass
func1(3, 5, 7)
#Out:15
def judger(*args, **kwargs): #函数定义时传来的参数,即3
def wrapper(func):
print(args)
def dec(*args, **kwargs): #函数执行时传递的参数,即2,4,5
"""do something"""
func(*args, **kwargs)
print(args)
return dec
return wrapper
@judger(3)
def func1(*args, **kwargs):
pass
func1(2,4,5)
#Out:
(3,)
(2, 4, 5)
from functools import wraps
def judger(*args, **kwargs):
@wraps(func)
def wrapper(func):
print(args)
wraps(func)
def dec(*args, **kwargs):
"""do something"""
func(*args, **kwargs)
print(args)
return dec
return wrapper
@judger(3)
def func1(*args, **kwargs):
pass
func1(2,4,5)