Python裝飾器用法實例分析
本文實例講述了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()
運行結(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')
運行結(jié)果:
before calling hello
hello haha
end calling hello
多個參數(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)
運行輸出:
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)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python實現(xiàn)發(fā)送聲情并茂的郵件內(nèi)容和附件
Python是一種高級編程語言,它可以用于編寫各種類型的應(yīng)用程序,包括發(fā)送電子郵件。本文就來演示如何使用Python發(fā)送HTML格式的電子郵件,感興趣的可以了解一下2023-04-04
基于Python實現(xiàn)nc批量轉(zhuǎn)tif格式
做項目有時會運用到netCDF格式的氣象數(shù)據(jù),而ArcGIS中需要用柵格影像進(jìn)行處理,對于較多的文件,ArcGIS一個個手動轉(zhuǎn)換過于繁瑣,因此我們采用Python進(jìn)行轉(zhuǎn)換,下面就是Python實現(xiàn)nc批量轉(zhuǎn)tif格式的示例代碼,希望對你有所幫助2022-08-08
Python中實現(xiàn)從目錄中過濾出指定文件類型的文件
這篇文章主要介紹了Python中實現(xiàn)從目錄中過濾出指定文件類型的文件,本文是一篇學(xué)筆記,實例相對簡單,需要的朋友可以參考下2015-02-02

