Python基礎day-7[閉包,裝飾器]

來源:互聯網
上載者:User

標籤:art   內容   turn   python   包含   dom   time   最簡   port   

閉包:

  首先說下閉包是什嗎?

    閉包就是在函數內部定義的函數,包含對外部範圍的引用,但不包含全域範圍。因為函數的範圍在定義的時候就固定死了,所以閉包函數有內建範圍和延遲計算的特點。

  閉包函數定義:如果一個內建函式,包含了對外部範圍的引用,但是不是包含全域範圍。那麼這個函數就被認為是閉包函數。閉包函數可以使用“.__closure__” 來查看閉包函數的屬性。下面我們來看一個樣本:

def t():    money = 100    def s():        print(money)    return s            #返回函數s,不是函數執行過的值c = t()c()print(c.__closure__)   #查看屬性執行結果:D:\Python\Python36-32\python.exe E:/Python/DAY-7/day7_筆記.py100(<cell at 0x00A4C3D0: int object at 0x60625D20>,)Process finished with exit code 0

  函數s就是在函數t中定義的內建函式

  函數s引用了一個外部的變數money,但是不是全域變數。則函數s就是一個閉包函數。

裝飾器:

  裝飾器本質可以是任意可調用對象,被裝飾的對象也可以是任意可調用對象。

  裝飾器功能:

    在不修改被裝飾對象原始碼以及調用方式的前提下,為其添加新的功能。

  裝飾器的文法:

    在被裝飾對象的正上方的單獨一行,@裝飾器名字。會把正下方的函數名調用裝飾器,處理完返回給函數名。

    多個裝飾器:誰在上面誰先執行,誰在下面誰先計算。

樣本:

import time          #匯入模組import randomdef timmer(func):   #裝飾器模組    def wrapper():    #定義一個閉包函數wrapper        stime = time.time()    #閉包函數內 計算index的睡眠時間 ,這裡是開始計算        func()      #執行index的函數內容        stptime = time.time()    #index的函數執行完畢後的停止時間        print(‘run time is %s‘%(stptime-stime))    #列印運行了多久    return wrapper()def index():  #定義函數index    time.sleep(random.randrange(1,2))   #函數內執行睡一定時間,然後列印 歡迎資訊    print(‘welecome to index page‘) index = timmer(index)    #調用裝飾器運行結果:D:\Python\Python36-32\python.exe E:/Python/DAY-7/tmp.pywelecome to index pagerun time is 1.0000858306884766Process finished with exit code 0

  上面這個是最簡單的裝飾器樣本。如果我們還要傳參,讓使用者感覺不出裝飾器的怎麼辦?我們來看下面的。

樣本:

import timeimport random#裝飾器def timmer(func):    def wrapper(*args,**kwargs):     #接受可變長參數        start_time = time.time()        res=func(*args,**kwargs)        #接收儲存對應函數 的return 傳回值        stop_time=time.time()        print(‘run time is %s‘ %(stop_time-start_time))        return res      #執行完畢 return 函數的傳回值    return wrapper#被裝飾函數@timmer              #使用@方式調用裝飾器def index():    time.sleep(random.randrange(1,5))    print(‘welecome to index page‘)@timmerdef home(name):           #需求一個傳入參數    time.sleep(random.randrange(1,3))    print(‘welecome to %s HOME page‘ %name)    return 123123123123123123123123123123123123123123     #return 有傳回值index()      #調用 無參數傳入print(home(‘abc‘))    #調用傳入參數‘abc’執行結果:D:\Python\Python36-32\python.exe E:/Python/DAY-7/tmp.pywelecome to index pagerun time is 2.0000545978546143welecome to abc HOME pagerun time is 2.0000154972076416123123123123123123123123123123123123123123Process finished with exit code 0

 

Python基礎day-7[閉包,裝飾器]

聯繫我們

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