本文實例講述了Python裝飾器用法。分享給大家供大家參考,具體如下:
無參數的裝飾器
#coding=utf-8def log(func): def wrapper(): print 'before calling ',func.__name__ func() print 'end calling ',func.__name__ return wrapper@logdef hello(): print 'hello'@logdef hello2(name): print 'hello',nameif __name__=='__main__': hello()
運行結果:
before calling hello
hello
end calling hello
帶參數的裝飾器:
#coding=utf-8def log(func):  def wrapper(name):    print 'before calling ',func.__name__    func(name)    print 'end calling ',func.__name__  return wrapper@logdef hello(name):  print 'hello',name@logdef hello2(name):  print 'hello',nameif __name__=='__main__':  hello('haha')運行結果:
before calling hello
hello haha
end calling hello
多個參數的時候:
#coding=utf-8def log(func):  '''  *無名字的參數  **有名字的參數  :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@logdef hello(name,age):  print 'hello',name,age@logdef hello2(name):  print 'hello',nameif __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
裝飾器里帶參數的情況
本質就是嵌套函數
#coding=utf-8def 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@logdef hello2(name):  print 'hello',nameif __name__=='__main__':  hello('haha',2)運行輸出:
INFO before calling hello
INFO args ('haha', 2) kvargs {}
hello haha 2
INFO end calling hello
更多關于Python相關內容可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答