装饰器
1.普通函数
#简单的函数和调用 def a1(): print("i am zhangsan") def a2(): print("i am lisi") a1() a2()
2.在函数前后添加功能
def inner(func): print("添加1") func() print("添加2") return func def a1(): print("i am zhangsan") def a2(): print("i am zhangsan") a1=inner(a1) a1() a2=inner(a2) a2()
3.使用装饰器
def mywork(func): def inner(): print("添加1") func() print("添加2") return inner @mywork # @mywork就等于a1=mywork(a1) def a1(): print("i am zhangsan") a1() #执行时@mywork会把他下面的函数当成mywork函数的参数既mywork(a1),然后在函数inner里执行,inner内func()=a1()
4.装饰带参数的函数
def mywork(func): def inner(arg): print("添加1") func(arg) print("添加2") return inner @mywork def a1(arg): print 'i am zhangsan',arg a1("参数1")
5.装饰动态参数的函数
#合并无参,有参,多参 可以装饰含有N个参数的函数 def mywork(func): def inner(*args,**kwargs): print("添加1") func(*args,**kwargs) print("添加2") return inner @mywork def a1(): print 'i am zhangsan' @mywork def a2(arg): print 'i am zhangsan',arg @mywork def a3(arg1,arg2): print 'i am zhangsan',arg1,arg2 a1() a2("参数1") a3("参数1","参数2")
6.装饰含有返回值的函数
#装饰含有返回值的函数 def mywork(func): def inner(*args,**kwargs): print("添加1") aa=func(*args,**kwargs) print("添加2") return aa return inner @mywork def a3(arg1,arg2): print 'i am zhangsan',arg1,arg2 li=[1,2,3,4,5,6] return li #返回一个列表 list=a3("参数1","参数2") #list等于inner的返回值 print(list) #li列表是a3的返回值,所以给在inner函数里执行的func()赋给aa,在通过inner的返回值就能拿到列表
7.装饰器实现登录验证简单原理
def login(): name =raw_input("输入用户名:") if name == "zhangsan": return True else: return False def mywork(func): def inner(*args,**kwargs): lo_login = login() if not lo_login: #如果login()返回的是False return "用户名错误!" aa=func(*args,**kwargs) return aa return inner @mywork def a3(arg1,arg2): print 'i am zhangsan',arg1,arg2 li=[1,2,3,4,5,6] return li list=a3("参数1","参数2") #list等于inner的返回值 print(list)
8.多个装饰器装饰一个函数
def newwork1(func): def inner(): print("newwork1前") func() print("newwork1后") return inner def newwork2(func): def inner(): print("newwork2前") func() print("newwork2后") return inner @newwork2 @newwork1 def f1(): print 'i am zhangsan' f1() ''' 输出结果: newwork1前 newwork2前 i am zhangsan newwork2后 newwork1后 '''
9.装饰器加参数
#3层装饰器 def Filter(a1,a2): def outer(func): def wrapper(request,kargs): print(a1) result=func(request,kargs) print(a2) return result return wrapper return outer aa=11 bb=22 @Filter(aa,bb) def Index(request,kargs): print request,kargs Index("zhangsan","lisi") #@Filter(aa,bb)会先执行Filter(aa,bb)函数,获取到返回值outer后拼接成@outer,之后就变成普通的装饰器了 #wrapper函数内可以使用a1,a2,request,kargs 4个参数