import requests
import time
url = 'http://www.baidu.com'
# 不含参数的装饰器,两个套
def alltime(func):
def wrapper(*args,**kwargs):
start = time.time()
content = func(*args,**kwargs)
print(time.time() - start)
return content
return wrapper
@alltime
def request():
content = requests.get(url)
return content
# 含参数的装饰器,三个套
def out(canshu):
def cehi(func):
def wrapper(*args,**kwargs):
# 可以理解为闭包中的global,在内部函数中修改外部函数的值
nonlocal canshu
while int(canshu) < 100:
start= time.time()
time.sleep(2)
content = func(*args,**kwargs)
print('本次用时%s' % (time.time()-start))
canshu = int(canshu) + 1
# 被装饰的函数有返回值的情况下需要返回
return content
return wrapper
return cehi
@out(canshu=30)
def xx():
print(123)
xx()
网友评论