本文實例講述了Python裝飾器模式定義與用法。分享給大家供大家參考,具體如下:
裝飾器模式定義:動態(tài)地給一個對象添加一些額外的職責。
在Python中Decorator mode可以按照像其它編程語言如C++, Java等的樣子來實現(xiàn),但是Python在應用裝飾概念方面的能力上遠不止于此,Python提供了一個語法和一個編程特性來加強這方面的功能。
首先需要了解一下Python中閉包的概念:如果在一個內(nèi)部函數(shù)里,對在外部作用域(但不是在全局作用域)的變量進行引用,那么內(nèi)部函數(shù)就被認為是閉包(closure)。
def makeblod(fn): def wrapped(): return '<b>'+fn()+'</b>' return wrappeddef makeitalic(fn): def wrapped(): return '<i>'+fn()+'</i>' return wrapped@makeblod@makeitalicdef hello(): return 'hello world'print hello()
運行結果:
<b><i>hello world</i></b>
def deco(arg):  def _deco(func):    def __deco():      print "before %s called [%s]." % (func.__name__, arg)      func()      print "after %s called [%s]." % (func.__name__, arg)    return __deco  return _deco@deco("mymodule")def myfunc():  print "myfunc() called."myfunc()運行結果:
before myfunc called [mymodule].
myfunc() called.
after myfunc called [mymodule].
希望本文所述對大家Python程序設計有所幫助。
 
  | 
新聞熱點
疑難解答
圖片精選