Python入門5

來源:互聯網
上載者:User

標籤:不能   技術   png   div   固定   image   產生器   tor   port   

裝飾器

裝飾器英文Decorator,自身是一個函數,用來封裝其它的函數,實現在不改變原來代碼的情況下,增加新的功能,返回一個修改後的函數對象,

裝飾器功能:

1、裝飾器也是函數

2、在不改變原有代碼的情況下,增加新的功能 

3、符合開放-封閉原則

在學習裝飾器之前,我們複習一下函數的相關概念

理解函數也是變數

當我們執行函數不加括弧的時候,輸出函數的記憶體位址:

def foo():    print(‘hello‘)print(foo)# 輸出<function foo at 0x0000000002CBCBF8>

當我們加上括弧後,輸出

def foo():    print(‘hello‘)foo()# 輸出hello
高階函數:

1、把一個函數名當做實參傳給另外一個函數

def bar():    print(‘bar‘)def t1(func):    func()t1(bar)# 輸出bar

2、傳回值中包含函數名

def bar():    print(‘bar‘)def t1(func):    return funcprint(t1(bar))# 輸出<function bar at 0x000000000303CBF8>
函數嵌套 
def foo():    print(‘foo‘)    def bar():        print(‘bar‘)    bar()foo()

前面做了那麼多的鋪墊,都是為了後邊的裝飾器,裝飾器的組成離不開高階函數+函數嵌套

無參數裝飾器
def logger(func):    def inner():        print(‘logger start‘)        res = func()        print(‘logger stop‘)        return res    return inner@loggerdef test1():    print(‘test1‘)def test2():    print(‘test2‘)test1()test2()# 輸出logger starttest1logger stoptest2
帶固定參數裝飾器
def logger(func):    def inner(arg):        print(‘logger start‘)        res = func(arg)        print(‘logger stop‘)        return res    return inner@loggerdef test1():    print(‘test1‘)@loggerdef test2(name):    print(‘test2‘, name)# test1()test2(‘chen‘)# 輸出logger starttest2 chenlogger stop

但是這個時候我的test1函數不能調用了,因為它沒有參數,怎麼解決,讓test1沒有參數,test2帶參數都可以是用呢?

非固定參數裝飾器
def logger(func):    def inner(*args, **kwargs):        print(‘logger start‘)        res = func(*args, **kwargs)        print(‘logger stop‘)        return res    return inner@loggerdef test1():    print(‘test1‘)@loggerdef test2(name):    print(‘test2‘, name)test1()test2(‘chen‘)
終極版
def logger(write_type):    # print(write_type)    def outer_wrapper(func):        def inner(*args, **kwargs):            if write_type == ‘file‘:                print(‘logger start‘)                res = func(*args, **kwargs)                print(‘logger stop‘)                return res            elif write_type == ‘db‘:                print(‘no support db‘)        return inner    return outer_wrapper@logger(write_type=‘file‘)def test1():    print(‘test1‘)    return ‘return test1‘@logger(write_type=‘db‘)def test2(name):    print(‘test2‘, name)a = test1()print(a)test2(‘chen‘)# 輸出logger starttest1logger stopreturn test1no support db

 

 

產生器

1、產生器只有在調用時候,才會產生相應的資料

2、

 

 

json和pickle

 

Python入門5

聯繫我們

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