什么是python装饰器?
python
装饰器其实也就是一个函数,一个用来包装函数的函数,返回一个修改以后的函数对象,将其从新赋值原来的标识符,并永久丧失对原始函数对象的访问。app
eg:当须要在Func1和Func2中加同样的功能时,能够在outer中添加一次就能够完成所有函数的添加。装饰器与函数创建链接的方式是在函数的前一行用@+装饰器名称来完成。而且在装饰器中必定要返回被装饰的对象ide
def outer(fun): def wrapper(): print '验证' fun() print 'zhuangshiq' return wrapper#必定要返回装饰器的对象 @outer #装饰器与函数创建链接 def Func1(): print 'func1' @outer def Func2(): print 'func2' Func1() Func2()
装饰器参数:函数
若函数中有接受的参数,则必须在装饰器中添加一个参数。而且在装饰器内部的函数调用中也要添加函数调用。spa
def outer(fun): def wrapper(arg):#arg为形参 print '验证' print arg fun(arg) print 'zhuangshiq' return wrapper @outer #装饰器与函数创建链接 def Func1(arg): print 'func1',arg @outer def Func2(arg): print 'func2',arg Func1('a') Func2('a')