裝飾器1.普通函數#簡單的函數和調用def a1(): print("i am zhangsan")def a2(): print("i am lisi")a1()a2()2.在函數前後添加功能def inner(func): print("添加1") func() p...
裝飾器
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)View Code
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後 '''View Code
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個參數