装饰器模式定义:动态地给一个对象添加一些额外的职责。
在Python中Decorator mode可以按照像其它编程语言如C++,java等的样子来实现,但是Python在应用装饰概念方面的能力上远不止于此,Python提供了一个语法和一个编程特性来加强这方面的功能。
首先需要了解一下Python中闭包的概念:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。
defmakeblod(fn):defwrapped():return'<b>'+fn()+'</b>'returnwrappeddefmakeitalic(fn):defwrapped():return'<i>'+fn()+'</i>'returnwrapped
@makeblod
@makeitalicdefhello():return'hello world'PRinthello()
defdeco(arg):def_deco(func):def__deco():print"before %s called [%s]."% (func.__name__, arg)
func()print"after %s called [%s]."% (func.__name__, arg)return__decoreturn_deco
@deco("mymodule")defmyfunc():print"myfunc() called."myfunc()
闭包学习:
http://blog.csdn.net/marty_fu/article/details/7679297