装饰器 (wrapper)
本质就是函数,为其他函数添加附加功能。
原则:
不修改被修饰函数的源代码
不修改被修饰函数的调用方式
开放封闭原则
开放:对扩展是开放的
封闭:对修改是封闭的
装饰器的固定格式:
1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 4 def wrapper(i): #装饰器函数,i是被装饰的函数 5 def times(*args,**kwargs): 6 """"在被装饰函数之前要做的事"""" 7 ret = i(*args,**kwargs) #被装饰函数 8 """"在被装饰函数之后要做的事"""" 9 return ret 10 return times 11 @wrapper #语法糖 @装饰器函数名 12 def foo(): #被装饰的函数 13 pass 14 foo()
查询程序运行时间的装饰器需要调用time模块
1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 4 import time 5 from functools import wraps 6 def times(i): 7 @wraps(i) #装饰器函数 8 def times1(*args,**kwargs): 9 stort = time.time() 10 ret=i(*args,**kwargs) #被装饰函数 11 stop = time.time() 12 print("函数的运行时间是%s"%(stop-stort)) 13 return ret 14 return times1 15 16 @times #语法糖 @装饰器函数名 17 def foo(name): #被装饰的函数 18 time.sleep(5) 19 print("同学们好,老师好",name) 20 return "新年好" 21 print(foo.__name__) 22 res=foo("xing") 23 print(res) 24 25 #输出 26 foo 27 同学们好,老师好 xing 28 函数的运行时间是5.000286102294922 29 新年好
用装饰器记录函数调用,并保存在文件中
#!/usr/bin/env python # -*- coding:utf8 -*- def log(func): def inner(*args,**kwargs): with open("a.txt","a",encoding="utf-8") as f: f.write(func.__name__+"\n") ret=func(*args,**kwargs) return ret return inner @log def shoping_add(): print("添加物品") @log def shoping_del(): print("删除物品") shoping_add() shoping_del() #输出 添加物品 删除物品 #会在当前路径生成一个a.txt文件 里面储存了添加物品,删除物品这几个字
带参数装饰器,控制装饰器函数运行
1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 4 import time 5 FLAG = True #如果FLAG = False则装饰器不运行 6 def times(flag): 7 def time1(func): 8 def time2(*args,**kwargs): 9 if FLAG == True: 10 start = time.time() 11 ret = func(*args,**kwargs) 12 stop = time.time() 13 print("函数执行时间是%s"%(stop-start)) 14 return ret 15 else: 16 ret = func(*args,**kwargs) 17 return ret 18 return time2 19 return time1 20 @times(FLAG) 21 def yl(): 22 time.sleep(5) 23 print("雪碧,可乐,健力宝") 24 @times(FLAG) 25 def nn(): 26 time.sleep(5) 27 print("酸奶,君乐宝,养乐多") 28 29 yl() 30 nn() 31 #输出 32 雪碧,可乐,健力宝 33 函数执行时间是5.000285863876343 34 酸奶,君乐宝,养乐多 35 函数执行时间是5.000286102294922
多装饰器装饰函数
1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 4 def times(func): 5 def time1(): 6 print("这是第1个输出的") 7 func() #time2() 8 print("这是第4个输出的") 9 return time1 10 11 def timess(func): 12 def time2(): 13 print("这是第2个输出的") 14 func() 15 print("这是第3个输出的") 16 return time2 17 18 @times #times(hehe)-->times(time2)==time1 19 @timess #timess(hehe) == time2 20 def hehe(): 21 print("我不知道该说些什么") 22 hehe() 23 #输出 24 这是第1个输出的 25 这是第2个输出的 26 我不知道该说些什么 27 这是第3个输出的 28 这是第4个输出的 29 30 """装饰器times中被装饰函数前的代码 @times 31 装饰器timess中被装饰函数前的代码 @timess 32 被装饰函数 hehe() 33 装饰器timess中被装饰函数后的代码 @timess 34 装饰器times中被装饰函数后的代码 @times"""