Python裝飾器示例
阿新 • • 發佈:2018-07-05
end 判斷 flag port code turn time lee pen
簡單裝飾器實現:
import time #簡單裝飾器 def show_time(f): #嵌套函數 def inner(): begin = time.time() f() end = time.time() print(‘spend %s‘%(end-begin)) return inner @show_time #foo=show_time(foo) def foo(): print(‘foo...‘) time.sleep(1) foo()
不定長參數裝飾器:
#不定長參數,功能函數加參數def show_time(f): #嵌套函數 def inner(*a,**b): begin = time.time() f(*a,**b) end = time.time() print(‘spend %s‘%(end-begin)) return inner @show_time #foo=show_time(foo) def foo(*a,**b): sums=0 for i in a: sums+=i print(sums) time.sleep(1) foo(1,2,3,4,5)
裝飾器函數加參數:
#裝飾器函數加參數 def logger(flag): def show_time(f): #嵌套函數 def inner(*a,**b): begin = time.time() f(*a,**b) end = time.time() print(‘spend %s‘%(end-begin)) #判斷flag傳參,之後所做的事情 if flag == ‘true‘: print(‘哈哈哈哈‘) return inner return show_time #傳參為true,則執行logger的內容 @logger(‘tru1e‘) #@show_time def foo(*a,**b): sums=0 for i in a: sums+=i print(sums) time.sleep(1) foo(1,2,3,4,5)
Python裝飾器示例