1.对大批量函数添加装饰器,而且不定期的开关
# 多个装饰器,添加批量管理的开关 import time FLAG = False def outer(flag): def timer(f1): def inner(*args,**kwargs): if flag == True: start_time = time.time() ret = f1(*args,**kwargs) end_time = time.time() print(‘运行时间为 %s‘ % (end_time-start_time)) else: ret = f1(*args,**kwargs) return ret return inner return timer @outer(FLAG) def func1(a, b): print(‘func1开头 -- %s‘ % a) time.sleep(0.1) print(‘func1结尾 -- %s‘ % b) @outer(FLAG) def func2(a, b): print(‘func2开头 -- %s‘ % a) time.sleep(0.1) print(‘func2结尾 -- %s‘ % b) # func1开头 -- a # func1结尾 -- b # func2开头 -- c # func2结尾 -- d
2.使用装饰器进行登录检测
# 第二种情况 # 使用装饰器进行登陆检测,如果已经登陆,则不用再次登陆 # import time login_info = {‘alex‘:False} def login(func1): def inner(name): if login_info[name] != True: user = input(‘user: ‘) pwd = input(‘pwd: ‘) if user == ‘alex‘ and pwd == ‘alex3714‘: login_info[name] = True if login_info[name] == True: ret = func1(name) return ret return inner def timmer(f): def inner(*args,**kwargs): start_time = time.time() ret = f(*args,**kwargs) end_time = time.time() print(end_time-start_time) return ret return inner @login # index = login(index) -- inner @timmer def index(name): print(‘欢迎%s来到博客园首页---‘ % name) time.sleep(0.3) @login @timmer def manager(name): print(‘欢迎%s来到博客园管理界面---‘ % name) time.sleep(0.3) index(‘alex‘) manager(‘alex‘) index(‘alex‘) manager(‘alex‘) # user: alex # pwd: alex3714 # 欢迎alex来到博客园首页--- # 0.30012965202331543 # 欢迎alex来到博客园管理界面--- # 0.30124926567077637 # 欢迎alex来到博客园首页--- # 0.3006711006164551 # 欢迎alex来到博客园管理界面--- # 0.3006777763366699
3.多个装饰器装饰一个函数,结构类似套娃
# 多个装饰器装饰一个函数,结构类似于套娃结构 def wrapper1(f1): #f def inner1(): print(‘wrapper1 before func‘) f1() # f print(‘wrapper1 after func‘) return inner1 def wrapper2(f2): #inner def inner2(): print(‘wrapper2 before func‘) f2() # inner1 print(‘wrapper2 after func‘) return inner2 # 在装饰器执行的时候,是从下向上依次执行 @wrapper2 # f = wrapper2(inner1) --> inner2 @wrapper1 # f = wrapper1(f) --> inner1 def f(): print(‘in f‘) f() #inner2 # wrapper2 before func # wrapper1 before func # in f # wrapper1 after func # wrapper2 after func
# 运行过程 def wrapper1(f1): # 3- f1 = f def inner1(): print(‘wrapper1 before func‘) ## 14= f1() ## 15= f() print(‘wrapper1 after func‘) ## 17= return inner1 # 4- inner1 def wrapper2(f2): # 7- f2 = inner1 def inner2(): ## 11= print(‘wrapper2 before func‘) ## 12= f2() ## 13= inner1 print(‘wrapper2 after func‘) ## 18= return inner2 # 8- inner2 # 在装饰器执行的时候,是从下向上依次执行 # 当遇到多个装饰器装饰一个函数的时候,会一直向下走,直到找到被装饰的函数 # 是一个先往下走,再往上回的过程 @wrapper2 # 6- f = wrapper2(f) --> f = wrapper2(inner1) # 9- f = inner2 **** 装饰过程结束 @wrapper1 # 2- f = wrapper1(f) # 5- f = inner1 --> f def f(): # 1- 从找到的f开始 print(‘in f‘) ## 16= f() # 10- 开始调用 f()相当于inner2()
原文地址:https://www.cnblogs.com/gnaix/p/8993580.html
时间: 2024-11-13 01:05:21