Decorator
Open Closed Principle
- To expand is open, allowing the code to expand, adding new features
- Modifications are closed, you can not modify the source code and the function is called
Decorator
Without changing the original decorative function source code and is called by the premise, to add additional functionality
# 版本一,测试每个函数都要写一遍代码 import time def func1(): time.sleep(2) # 暂停2秒 print('测试延迟') time1 = time.time() # 返回的格林威治时间,是此时此刻距离1970年1月1日0时0分0秒的时间秒数,也叫时间戳 func1() time2 = time.time() print(time2-time1)
# 版本二 只能测试特定的函数 import time def func1(): time.sleep(2) print('测试延迟') def ceshi(): time1 = time.time() func1() time2 = time.time() print(time2-time1) ceshi()
# 版本三,虽然没有改变原函数的代码,但是改变了执行方式,不符合开放封闭原则 import time def func1(): time.sleep(2) print('测试延迟') def ceshi(func): time1 = time.time() func() time2 = time.time() print(time2-time1) ceshi(func1)
#版本四,实施真正的开放封闭原则:装饰器 import time def func1(): time.sleep(2) print('测试延迟') def timer(func): def ceshi(): time1 = time.time() func() time2 = time.time() print(time2-time1) return ceshi func1 = timer(func1) func1()
#带返回值的装饰器 import time def func1(): time.sleep(2) print('测试延迟') return '测试成功' def timer(func): def ceshi(): time1 = time.time() ret = func() time2 = time.time() print(time2-time1) return ret return ceshi func1 = timer(func1) print(func1())
# 被装饰函数带参数的装饰器 import time def func1(name): time1 = time.sleep(2) print(f'{name}测试延迟') return f'{name}测试成功' def timer(func): def ceshi(name): time1 = time.time() ret = func(name) time2 = time.time() print(time2-time1) return ret return ceshi func1=timer(func1) print(func1('太上老君'))
# 被装饰函数不定参数的装饰器 import time def func1(*args,**kwargs): time.sleep(2) print(f'{args}测试延迟') return f'{args,kwargs}测试成功' def timer(func): def ceshi(*args,**kwargs): time1 = time.time() ret = func(*args,**kwargs) time2 = time.time() print(time2-time1) return ret return ceshi func1 = timer(func1) print(func1('太上老君','元始天尊',我叫='通天教主'))
#标准装饰器:语法糖 import time def timer(func): #func=func1 def ceshi(*args,**kwargs): # args = ('太上老君', '元始天尊') # kwagrs = {'我叫'; '通天教主'} time1 = time.time() ret = func(*args,**kwargs) time2 = time.time() print(time2-time1) return ret return ceshi @timer # 相当于 func1 = timer(func1),没有特殊意义,为了简化 def func1(*args,**kwargs): time.sleep(2) print(f'{args,kwargs}测试延迟') return f'{args,kwargs}测试成功' print(func1('太上老君', '元始天尊', 我叫='通天教主'))