Python之裝飾器

來源:互聯網
上載者:User

標籤:code   style   調用   div   dap   記憶體   原則   password   rgs   

裝飾器的作用:在不改變原始碼和調用方式的情況下,實現功能的添加

(一)基礎的裝飾器(僅實現為函數添加功能)

     功能實現:

           為原函數添加計算已耗用時間的功能

            

‘‘‘高階函數+嵌套函數=>裝飾器裝飾器的原則:(1)不能改變被裝飾函數的原始碼(2)不能改變被裝飾函數的調用方式‘‘‘import timedef timer(func):    def func_deco(*args,**kwargs):        start_time=time.time()        func(*args,**kwargs)        run_time=time.time()-start_time        print("函數的已耗用時間為 %s" %run_time)    return func_deco  #返回函數啟動並執行記憶體位址@timerdef fun_te(name,age):    time.sleep(1)    print(name)    print(age)fun_te(‘lihanyu‘,18)

測試結果如所示:

 

(二)裝飾器高潮版

   情景實現為:在網站的登入過程中,一部分為本地登入(local),一部分為ldap登入,在判斷完登入方式以後,實現使用者登入功能。

 

import timeuser,pwd=(‘lihanyu‘,‘110‘)def out(auth_type):    def auth(func):        def wapper(*args,**kwargs):#可以實現傳任意個數的參數            if auth_type==‘local‘:                username=input("username:")                password=input("password:")                if username==user and password==pwd:                    print("驗證成功")                    res=func(*args,**kwargs)                    return res  #返回所運行函數的傳回值,此代碼中即為home()的傳回值                else:                    print("使用者名稱或密碼輸入錯誤")            elif auth_type==‘ldap‘:                print("我不懂啊。。。。。")            else:                print("沒有此種登入方式")        return wapper    return authdef index():    print("welcome to index")@out(auth_type=‘local‘)def home():    print(‘welcome to home page‘)    return "from home"@out(auth_type=‘ldap‘)def bbs():    print("welcome to bbs")index()print(home())bbs()

測試結果如所示:

 

 歡迎各位大神測試,指正,謝謝!

 

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.