裝飾器模式定義:動態(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()

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()
閉包學習:
http://blog.csdn.net/marty_fu/article/details/7679297
新聞熱點
疑難解答