在不改變原被裝飾函數的源代碼以及調用方式前提下,爲其添加額外功能python
# 版本一,測試每一個函數都要寫一遍代碼 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('太上老君', '元始天尊', 我叫='通天教主'))