4.装饰器基础篇
1.三个功能函数 f1,f2,f3
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5 import time def f1(): for i in range(100): print(i) def f2(): for i in range(1000): print(i) def f3(): for i in range(10000): print(i)
2.项目遇到性能瓶颈,需要统计各个函数执行的时间
第一种解决方案(红色部分为新加代码):
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5 import time def f1(): start_time = time.time() for i in range(100): print(i) end_time = time.time() print(end_time - start_time) def f2(): start_time = time.time() for i in range(1000): print(i) end_time = time.time() print(end_time - start_time) def f3(): start_time = time.time() for i in range(10000): print(i) end_time = time.time() print(end_time - start_time)
分析:为了统计各个函数执行的时间,修改了函数原有的代码,违反了代码设计的开放-封闭原则(对扩展开放,对修改关闭)
3.使用装饰器进行改进(红色部分为新加代码):
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5 import time def cal_consume_time(func): def wrapper(): start_time = time.time() func() end_time = time.time() print(end_time - start_time) return wrapper @cal_consume_time #等价于 f1 = cal_consume_time(f1) def f1(): for i in range(100): print(i) @cal_consume_time #等价于 f2 = cal_consume_time(f2) def f2(): for i in range(1000): print(i) @cal_consume_time #等价于 f3 = cal_consume_time(f3) def f3(): for i in range(10000): print(i)
分析:使用装饰器之后符合开放-关闭原则
(1)装饰器是以闭包为基础的(闭包在上一篇有介绍);
(2)f1函数的 @cal_consume_time 这个语法糖等价于:f1 = cal_consume_time(f1),所在以后调用 f1函数实际上调用的是 cal_consume_time(f1) 返回的函数
(3)装饰带参数的函数
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5 import time def cal_consume_time(func): def wrapper(*args): start_time = time.time() func(args) end_time = time.time() print(end_time - start_time) return wrapper @cal_consume_time def f1(*args): for i in range(100): print(i) print(args)
(4)装饰器升级版:
# -*- coding: utf-8 -*- #__author:jiangjing #date:2018/1/5 import time def cal_consume_time(flag): def decprator(func): def wrapper(*args): start_time = time.time() func(args) end_time = time.time() if flag == True: print(end_time - start_time) return wrapper return decprator @cal_consume_time(True) def f1(*args): for i in range(100): print(i) print(args) f1(-1, -2, -3)
posted on 2018-01-29 17:59 后端bug开发工程师 阅读(145) 评论(0) 编辑 收藏 举报