如何理解及使用Python閉包
一、Python 中的作用域規(guī)則和嵌套函數(shù)
每當執(zhí)行一個函數(shù)時,就會創(chuàng)建一個新的局部命名空間,它表示包含函數(shù)體內(nèi)分配的函數(shù)參數(shù)和變量名的局部環(huán)境。我們可以將名稱空間看作一個字典,其中鍵是對象名稱,值是對象本身。
解析名稱時,解釋器首先搜索本地命名空間。如果不存在匹配,則搜索全局名稱空間,該名稱空間是定義函數(shù)的模塊。如果仍然沒有找到匹配項,則在引發(fā) NameError 異常之前最終檢查內(nèi)置名稱空間。下圖說明了這一點:

讓我們考慮下面的例子:
age = 27 def birthday(): age = 28 birthday() print(age) # age will still be 27 >> 27
當變量在函數(shù)內(nèi)部賦值時,它們總是綁定到函數(shù)的本地名稱空間; 因此,函數(shù)體中的變量 age 指的是一個包含值28的全新對象,而不是外部變量。可以使用全局語句更改此行為。下面的示例強調(diào)了這一點:
age = 27 name = "Sarah" def birthday(): global age # 'age' is in global namespace age = 28 name = "Roark" birthday()# age is now 28. name will still be "Sarah"
Python 也支持嵌套函數(shù)定義(函數(shù)內(nèi)部的函數(shù)):
def countdown(start):
# This is the outer enclosing function
def display():
# This is the nested function
n = start
while n > 0:
n-=1
print('T-minus %d' % n)
display()
# We execute the function
countdown(3)
>>>
T-minus 3
T-minus 2
T-minus 1
二、定義閉包函數(shù)
在上面的示例中,如果函數(shù) countdown()的最后一行返回了 display 函數(shù)而不是調(diào)用它,會發(fā)生什么情況?這意味著該函數(shù)的定義如下:
def countdown(start):
# This is the outer enclosing function
def display():
# This is the nested function
n = start
while n > 0:
n-=1
print('T-minus %d' % n)
return display
# Now let's try calling this function.
counter1 = countdown(2)
counter1()
>>>
T-minus 2
T-minus 1
使用值2調(diào)用 countdown()函數(shù),并將返回的函數(shù)綁定到名稱 counter1。在執(zhí)行 counter1()時,它使用最初提供給 countdown ()的 start 值。因此,在調(diào)用 counter1()時,盡管我們已經(jīng)執(zhí)行了 count1()函數(shù),但仍然記住這個值。
這種將一些數(shù)據(jù)(本例中為2)附加到代碼的技術(shù)在 Python 中稱為閉包。
即使變量超出范圍或函數(shù)本身從當前名稱空間中移除,也會記住封閉范圍中的這個值。我們可以嘗試下面的代碼來確認:
>>> del countdown >>> counter1() T-minus 2 T-minus 1 >>> countdown(2) Traceback (most recent call last): ... NameError: name 'countdown' is not defined
三、何時使用閉包?
當一個類中實現(xiàn)的方法很少(大多數(shù)情況下只有一個方法)時,閉包可以提供一個替代的、更優(yōu)雅的解決方案。此外,如果我們希望根據(jù)延遲或延遲計算的概念編寫代碼,閉包和嵌套函數(shù)特別有用。下面是一個例子:
from urllib.request import urlopen def page(url): def get(): return urlopen(url).read() return get
在上面的示例中,page ()函數(shù)實際上并不執(zhí)行任何計算。相反,它只是創(chuàng)建并返回一個函數(shù) get () ,該函數(shù)在調(diào)用 web 頁面時獲取頁面內(nèi)容。因此,在 get ()中執(zhí)行的計算實際上被延遲到計算 get ()時程序中的某個后續(xù)點。例如:
>>> url1 = page("http://www.google.com")
>>> url2 = page("http://www.bing.com")
>>> url1
<function page.<locals>.get at 0x10a6054d0>
>>> url2
<function page.<locals>.get at 0x10a6055f0>
>>> gdata = url1() # Fetches http://www.google.com
>>> bdata = url2() # Fetches http://www.bing.com
>>>
可以找到閉包函數(shù)中包含的值。
所有函數(shù)對象都有一個 _closure_ 屬性,如果它是一個閉包函數(shù),那么這個屬性將返回一組單元格對象。根據(jù)上面的例子,我們知道 url1和 url2是閉包函數(shù)。
>>> page.__closure__ # Returns None since not a closure >>> url1.__closure__ (<cell at 0x10a5f1250: str object at 0x10a5f3120>,)
單元格對象具有存儲關(guān)閉值的屬性 cell_contents。
>>> url1.__closure__[0].cell_contents 'http://www.google.com' >>> url2.__closure__[0].cell_contents 'http://www.bing.com'
四、總結(jié)
當嵌套函數(shù)引用其封閉范圍中的值時,可以定義 Python 中的閉包。閉包提供了某種形式的數(shù)據(jù)隱藏。閉包還可以是一種高效的方法,可以在一系列函數(shù)調(diào)用之間保持狀態(tài)。用 Python 創(chuàng)建一個閉包函數(shù):
- 我們必須有一個嵌套的函數(shù)
- 嵌套函數(shù)必須引用封閉函數(shù)中定義的值
- 封閉函數(shù)必須返回嵌套函數(shù)
到此這篇關(guān)于如何理解及使用Python閉包的文章就介紹到這了,更多相關(guān)Python閉包內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信