python之裝飾器

來源:互聯網
上載者:User

標籤:func   pre   就是   div   裝飾器   其他   樣本   art   for   

 

一:裝飾本質就是函數,功能是為其他函數添加附加功能 

二:原則:

1)不修改被修飾函數的原始碼

2)不修改被修飾函數的調用方式

三:裝飾器的實現

1)裝飾器=高階函數+函數嵌套+閉包

樣本:將下列函數增加一個執行時間的功能

import timedef cal(l):    res=0    for i in l:        res+=i    return resret=cal(range(20))print(ret)

 此時為了保證裝飾器的原則,我們需要另外寫一個執行時間的函數

給函數添加裝飾器,實現列印出已耗用時間的功能def timer(func):    def wapper(*args,*kwargs):        starttime = time.time()        res = func(*args,**kwargs)        stoptime = time.time()        print("函數的已耗用時間為:%s" %(stoptime-starttime))        return  res    return wapper

  裝飾器的用法:在第一個函數中聲明一下即可@timer

@timerdef cal(l):    res=0    for i in l:        res+=i    return resret=cal(range(20))print(ret)

  

 

python之裝飾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.