python第十一天

來源:互聯網
上載者:User

標籤:pre   內容   python   cti   func   首頁   訪問   實現   簡單   

開始第二模組的學習:

裝飾器 :

描述:

裝飾器原則:

  1、不能修改被裝飾的函數的原始碼

  2、不能修改裝飾的函數的調用方試

 

實現裝飾器的需要:

  高階函數+嵌套函數=裝飾器

  高階函數:

      類型I:將函數做為實參的函數,可以稱為高階函數

        

1 def fun_1(fun_2):#fun_1 為高階函數2     print(‘1‘)3     fun_2()4 5 def fun_2():6     print(‘2‘)7 8 fun_1(fun_2)

 

      類型II:傳回值中包含函數名的函數,也可以稱為高階函數

      

def fun_3(fun):#fun_3 為高階函數    print(‘3‘)    return fundef fun_4():    print(‘4‘)#fun_3(fun_4)()#傳回值可以直接運行fun=fun_3(fun_4)#可以將傳回值賦於一個變數fun()#可以調用函數

 

  嵌套函數:

      在函數中定義一個新函數,這個函數稱為嵌套函數

    

1 def fun_5():#fun_5 為嵌套函數2     print(‘5‘)3     def fun_5_1():4         print(‘5.1‘)5     6 fun_5()

最簡單的裝飾:

 1 def fun_2(fun):#傳入fun_1的函數 2     def function(): 3      4         fun() 5         print(‘in the fun_2......‘)#增加新的內容 6      7     return function 8  9 @fun_2#裝飾fun_!  相當於fun_1=fun_2(fun_1)10 def fun_1():11     print("in the fun_1....")12 13 14 fun_1()

裝飾器: 類比登陸認證

 1 #類比網站登陸訪問認證 2 # 3 name=‘abc‘ 4 password=‘123‘ 5 def certi(model):#裝飾器 6     def outr(fun):#裝飾器加參數需要多加一層嵌套 7         def login(*args,**kwargs):#為了相容各類函數參數,添加 *args,**kwargs 不固定參數 8             if model==‘password‘: 9                 print(‘這是password認證‘)10                 user_name = input(‘使用者名稱:‘).strip()11                 paswd=input(‘密碼:‘).strip()12                 if user_name==name and paswd==password:    13                     print(‘通過認證‘)14                     return fun(*args,**kwargs)15                 else:16                     print(‘使用者或密碼錯誤 ,退出‘)17                     exit()18             elif model==‘lamp‘:19                 print(‘這是lamp認證‘)20                 return fun(*args,**kwargs)21             else:22                 print(‘認證出錯‘)23         return login24     return outr25 26 27 def indxe():28     print(‘歡迎進入首頁‘)29 30 @certi(model=‘password‘)31 def user():32     print(‘歡迎進入使用者頁面:‘)33 34 @certi(model=‘lamp‘)35 def bbs(name):36     print(‘歡迎%s登陸論壇!!‘%name)37 38 indxe()39 user()40 bbs(name=‘yjj‘)

 

  

python第十一天

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.