python 3.x 學習筆記5 (裝飾器),python3.x

來源:互聯網
上載者:User

python 3.x 學習筆記5 (裝飾器),python3.x

1.裝飾器

本質是函數,(裝飾其他函數)就是為其他函數添加附加功能

原則:

  1)不能修改被裝飾的函數的原始碼
  2)不能修改被裝飾的函數的調用方式

2.實現裝飾器知識儲備

  1)函數即“變數”

  2)高階函數

    a.把一個函數當作實參傳給另一個函數(可以做到不修改被裝飾函數的原始碼的情況下為其添加功能)

    b.傳回值中包含函數名)(不修改函數的調用方式)

  3)嵌套函數

3.高階函數+嵌套函數=》裝飾器

 

4.初步裝飾器

import timedef timer(func):              #timer(test1)  func = test1    def deco():        start_time = time.time()        func()                #run test1        stop_time = time.time()        print('the func run time is %s'%(stop_time-start_time))    return deco@timer              #test1 = timer(test1)def test1():    time.sleep(3)    print('in the test1')test1()

5.功能比較完善的裝飾器

 

user,passwd = 'hsj','1234'def auth(auth_type):    print('auth func:',auth_type)    def outer_wrapper(func):        def wrapper(*args, **kwargs):            print('wrapper:',*args, **kwargs)            if auth_type == 'local':                username = input('Username:').strip()                password = input('Password:').strip()                if username == user and password == passwd:                    print('\033[32;1mUser has pass authentication\033[0m')                    return func(*args, **kwargs)  # from home         #函數wrapper的傳回值                else:                    exit('\033[31;1mInvalid username or password\033[0m')            elif auth_type =='ldap':                print('ldappppppppp')        return wrapper    return outer_wrapperdef index():    print('welcome to index psge')@auth(auth_type='local')      # 加了括弧相當於運行了outer_wraper所以會執行裡面內容   # home = auth(home)def home():    print('welcome to home page')    return 'from home'         #這裡有傳回值在裝飾器裡也應該有個傳回值不然是print()不出來的@auth(auth_type='ldap')def bbs():    print('welcome to bbs page')index()print(home())bbs()

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.