標籤:cti 修改 調用 time() time span strong else sleep
裝飾器的作用:擴充函數功能。
特點:1.不修改原函數代碼
2.保持調用函數不變
原理:高階函數 + 嵌套函數 = 裝飾器
1 # Author = Johnston 2 import time 3 def timer(func): 4 def deco(): 5 start_time = time.time() 6 func() 7 end_time = time.time() 8 print("the function run time is %s" %(end_time-start_time)) 9 return deco10 11 @timer #bar = timer(bar),@time必須寫在需裝飾的函數前面12 def bar():13 time.sleep(3)14 print("in the bar")15 16 bar()
無參數裝飾器
# Author = Johnstonimport timedef timer(func): def deco(name): #傳遞參數name start_time = time.time() func(name) end_time = time.time() print("the function run time is %s" %(end_time-start_time)) return deco@timer #bar = timer(bar),@timer必須寫在需裝飾的函數前面def bar(name): time.sleep(3) print("%s is in the bar" %name)bar("Johnston")
內參裝飾器
1 # Author = Johnston 2 import time 3 def outpara(type): 4 def timer(func): 5 def deco(name): 6 if type==1: #根據外參數作為判斷執行條件 7 start_time = time.time() 8 func(name) 9 end_time = time.time()10 print("the function run time is %s" %(end_time-start_time))11 else:12 print("wrong type")13 return deco14 return timer15 16 @outpara(type=1) #傳遞條件參數,@outpara必須寫在需裝飾的函數前面
17 def bar(name):
18 time.sleep(3)
19 print("%s is in the bar" %name)
20
21 bar("Johnston")
外參裝飾器
Python3 之裝飾器