Python3 之裝飾器

來源:互聯網
上載者:User

標籤: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 之裝飾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.