Python函數(八)-裝飾器(一)

來源:互聯網
上載者:User

標籤:top   log   func   技術   通過   python   複雜   inf   class   

裝飾器通過函數來定義,用來裝飾函數

裝飾器不改變被裝飾函數的原始碼和運行方式

如何?這個效果呢?

# -*- coding:utf-8 -*-__author__ = "MuT6 Sch01aR"import timedef timer(func): #定義一個裝飾器    def deco():        start_time = time.time()        func()        stop_time = time.time()        print("the run time is %s"%(stop_time-start_time))    return decodef test1():    time.sleep(3)    print(‘in the test1‘)test1 = timer(test1)test1()

既沒有改變被裝飾函數的原始碼,也沒有改變它的運行方式

運行

這麼寫有些複雜,可以直接在函數前調用裝飾器

調用裝飾器的格式為:@裝飾器名

# -*- coding:utf-8 -*-__author__ = "MuT6 Sch01aR"import timedef timer(func): #定義一個裝飾器    def deco():        start_time = time.time()        func()        stop_time = time.time()        print("the run time is %s"%(stop_time-start_time))    return deco@timer #相當於test1 = timer(test1)def test1():    time.sleep(3)    print(‘in the test1‘)test1()

運行

執行過程:

先走test1函數前的裝飾器timer(),然後在timer()函數內走函數deco(),記錄下start_time,然後deco()函數調用函數test1(),然後執行完函數test1()後,記錄下stop_time,最後計算時間並列印

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.