装饰器,不改变原来的函数,给函数添加新功能,可以自己写,也有写好的
1 def timer(func):
2 def war(*args,**kwargs):
3 start= time.time()
4 res = func(*args,**kwargs)
5 end_time = time.time()
6 print('运行时间是%s'%(end_time-start))
7 return res
8 return war
用装饰器记录下载图片的时间:
1 import requests
2 @timer#用计时的装饰器
3 def down_img():#下载网页上的图片到本地
4 res = requests.get('http://www.nnzhp.cn:80/wp-content/uploads/2018/07/60f2add20f0659e27d26435f28b8472e.png')
5 open('a.png','wb').write(res.content)
6 down_img()
运行结果:
也可以传参有返回值