Python裝飾器用法實(shí)例分析
本文實(shí)例講述了Python裝飾器用法。分享給大家供大家參考,具體如下:
無參數(shù)的裝飾器
#coding=utf-8 def log(func): def wrapper(): print 'before calling ',func.__name__ func() print 'end calling ',func.__name__ return wrapper @log def hello(): print 'hello' @log def hello2(name): print 'hello',name if __name__=='__main__': hello()
運(yùn)行結(jié)果:
before calling hello
hello
end calling hello
帶參數(shù)的裝飾器:
#coding=utf-8 def log(func): def wrapper(name): print 'before calling ',func.__name__ func(name) print 'end calling ',func.__name__ return wrapper @log def hello(name): print 'hello',name @log def hello2(name): print 'hello',name if __name__=='__main__': hello('haha')
運(yùn)行結(jié)果:
before calling hello
hello haha
end calling hello
多個(gè)參數(shù)的時(shí)候:
#coding=utf-8 def log(func): ''' *無名字的參數(shù) **有名字的參數(shù) :param func: :return: ''' def wrapper(*args,**kvargs): print 'before calling ',func.__name__ print 'args',args,'kvargs',kvargs func(*args,**kvargs) print 'end calling ',func.__name__ return wrapper @log def hello(name,age): print 'hello',name,age @log def hello2(name): print 'hello',name if __name__=='__main__': hello('haha',2) hello(name='hehe',age=3)
輸出:
end calling hello
before calling hello
args () kvargs {'age': 3, 'name': 'hehe'}
hello hehe 3
end calling hello
裝飾器里帶參數(shù)的情況
本質(zhì)就是嵌套函數(shù)
#coding=utf-8 def log(level,*args,**kvargs): def inner(func): def wrapper(*args,**kvargs): print level,'before calling ',func.__name__ print level,'args',args,'kvargs',kvargs func(*args,**kvargs) print level,'end calling ',func.__name__ return wrapper return inner @log(level='INFO') def hello(name,age): print 'hello',name,age @log def hello2(name): print 'hello',name if __name__=='__main__': hello('haha',2)
運(yùn)行輸出:
INFO before calling hello
INFO args ('haha', 2) kvargs {}
hello haha 2
INFO end calling hello
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python 實(shí)現(xiàn)生成均勻分布的點(diǎn)
今天小編就為大家分享一篇python 實(shí)現(xiàn)生成均勻分布的點(diǎn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12python中sys.argv參數(shù)用法實(shí)例分析
這篇文章主要介紹了python中sys.argv參數(shù)用法,實(shí)例分析了python中sys.argv參數(shù)的功能、定義及使用技巧,需要的朋友可以參考下2015-05-05python 用Matplotlib作圖中有多個(gè)Y軸
這篇文章主要介紹了python 如何用Matplotlib作圖中有多個(gè)Y軸,幫助大家更好的利用python繪圖,感興趣的朋友可以了解下2020-11-11Python中range、np.arange和np.linspace的區(qū)別
本文主要介紹了Python中range、np.arange和np.linspace的區(qū)別,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03python 從csv讀數(shù)據(jù)到mysql的實(shí)例
今天小編就為大家分享一篇python 從csv讀數(shù)據(jù)到mysql的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06