python函數學習之裝飾器

來源:互聯網
上載者:User

標籤:開放封閉原則   python函數   文法   它的   login   澳門   函數對象   執行函數   學習   

裝飾器

裝飾器的本質是一個python函數,它的作用是在不對原函數做任何修改的同時,給函數添加一定的功能。裝飾器的傳回值也是一個函數對象。

分類:1、不帶參數的裝飾器函數:
def wrapper(f):                    #裝飾器    def inner():        ‘‘‘執行函數之前要做的‘‘‘        print(‘葫蘆娃葫蘆娃,一根藤上七個娃。‘)
     ret = f() ‘‘‘執行函數之後要做的‘‘‘
     print(‘風吹雨打都不怕,啦啦啦啦~‘) return ret return inner@wrapper #文法糖 @wrapper 相當於 func = wrapper(func)def func(*args,**kwargs): print("澳門頂級賭場上線啦,性感荷官線上發牌,讓您嗨翻天~")func() #func() = inner() 調用裝飾器

計算結果:
葫蘆娃葫蘆娃,一根藤上七個娃。
澳門頂級賭場上線啦,性感荷官線上發牌,讓您嗨翻天~
風吹雨打都不怕,啦啦啦啦~

  其中wrapper()就是裝飾器函數,func()為被裝飾函數,被裝飾之後func()可以實現inner中的一部分功能。

2、帶參數的裝飾器函數:
def timer(func):    def inner(*args,**kwargs):        print("大頭兒子小頭爸爸,一對好朋友快樂父子倆。")        ret = func(*args,**kwargs)        print("兒子的頭大手兒很小,爸爸的頭小手兒很大。")        return ret    return inner@timerdef func(name):    print("%s是隔壁王叔叔"%name)func("王文勁")計算結果:大頭兒子小頭爸爸,一對好朋友快樂父子倆。王文勁是隔壁王叔叔兒子的頭大手兒很小,爸爸的頭小手兒很大。
原則:開放封閉原則

1、開放:對拓展是開放的,可以添加新功能(裝飾器)

2、封閉:對修改是封閉的,不能輕易修改以前的代碼

應用:
使用者登入檢測
運用——登入檢測:user,pw=‘jaye‘,‘88888888‘login_status = Falsedef login():    if login_status == False:        if auth_type =="jingdong"            username = input()            password = input()            if user == username and pw == password:                print(‘welcome to moubao store‘)                home()                login_status = True        elif auth_type =="weixin"            ...    else:        pass@login(auth_type = ‘jingodng‘)def home():    print(‘welcome to home page‘)@login(auth_type = ‘weixin‘)def finance():    print(‘welcome to home page‘)@login(auth_type = ‘jingodng‘)def book():    print(‘welcome to home page‘)

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.