這篇文章主要介紹了python裝飾器使用實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
python裝飾器的作用就是在不想改變?cè)瘮?shù)代碼的情況下,增加新的功能.主要應(yīng)用了python閉包的概念,現(xiàn)在用1個(gè)小例子說明
import timedef foo(): time.sleep(1) def bar(): time.sleep(2) def show_time(f): def inner(): start_time = time.time() f() end_time = time.time() print(end_time-start_time) return inner#show_time(f) is a decoration functionfoo = show_time(foo)bar = show_time(bar)foo()bar()
上面的代碼定義了兩個(gè)函數(shù)foo()和bar(). 通過裝飾器函數(shù)show_time(f),在其內(nèi)部定義了另一個(gè)閉包函數(shù)inner(),再通過foo=show_time(foo),bar=show_time(bar)語句將foo()和bar()函數(shù)同裝飾器函數(shù)關(guān)聯(lián)起來,從而實(shí)現(xiàn)了不改變foo()和bar()函數(shù)代碼,增加打印程序執(zhí)行時(shí)間的功能.程序的執(zhí)行結(jié)果如下:
1.00113701822.00142788887
顯然,程序在沒有改變?cè)瘮?shù)的情況下,實(shí)現(xiàn)了調(diào)用原函數(shù)顯示程序運(yùn)行時(shí)間的功能.
上面的小程序可以將調(diào)用裝飾器的語句改成@decoration的形式,效果是造價(jià)的,改變后的程序如下,其功能和上面的程序完全相同.
import time@show_time #foo = show_time(foo)def foo(): time.sleep(1) @show_time #bar = show_time(bar)def bar(): time.sleep(2) def show_time(f): def inner(): start_time = time.time() f() end_time = time.time() print(end_time-start_time) return inner#show_time(f) is a decoration functionfoo()bar()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)之家。
新聞熱點(diǎn)
疑難解答
圖片精選