python閉包技巧 Python閉包

2021-10-21 07:59:16 字數 2539 閱讀 2985

本篇文章幫大家學習python閉包,包含了python閉包使用方法、操作技巧、例項演示和注意事項,有一定的學習價值,大家可以用來參考。

在本文中,您將了解什麼是python閉包,如何定義閉包以及應該如何使用閉包。

巢狀函式中的非區域性變數

在進入閉包之前,我們必須先了解乙個巢狀函式和非區域性變數。

在函式中定義另乙個函式稱為巢狀函式。巢狀函式可以訪問包圍範圍內的變數。

在python中,這些非區域性變數只能在預設情況下讀取,我們必須將它們顯式地宣告為非區域性變數(使用nonlocal關鍵字)才能進行修改。

以下是訪問非區域性變數的巢狀函式的示例。

def print_msg(msg):

# this is the outer enclosing function

def printer():

# this is the nested function

print(msg)

printer()

# we execute the function

# output: hello

print_msg("hello")

可以看到巢狀函式printer()能夠訪問封閉函式的非區域性變數msg。

定義閉包函式

在上面的例子中,如果函式print_msg()的最後一行返回printer()函式而不是呼叫它,會發生什麼? 如該函式定義如下 -

def print_msg(msg):

# this is the outer enclosing function

def printer():

# this is the nested function

print(msg)

return printer # this got changed

# now let's try calling this function.

# output: hello

another = print_msg("hello")

another()

這樣是不尋常的。

print_msg()函式使用字串「hello」進行呼叫,返回的函式被繫結到另乙個名稱。 在呼叫another()時,儘管我們已經完成了print_msg()函式的執行,但仍然記住了這個訊息。

一些資料(「hello」)附加到**中的這種技術在python中稱為閉包。

即使變數超出範圍或函式本身從當前命名空間中刪除,也會記住封閉範圍內的值。

嘗試在python shell中執行以下內容以檢視輸出。

>>> del print_msg

>>> another()

hello

>>> print_msg("hello")

traceback (most recent call last):

nameerror: name 'print_msg' is not defined

什麼時候閉包?

從上面的例子可以看出,當巢狀函式引用其封閉範圍內的值時,在python中有使用了乙個閉包。

在python中建立閉包必須滿足的標準將在以下幾點 -

必須有乙個巢狀函式(函式內部的函式)。

巢狀函式必須引用封閉函式中定義的值。

閉包函式必須返回巢狀函式。

何時使用閉包?

那麼閉包是什麼好的?

閉包可以避免使用全域性值並提供某種形式的資料隱藏。它還可以提供物件導向的解決問題的解決方案。

當在類中幾乎沒有方法(大多數情況下是一種方法)時,閉包可以提供乙個替代的和更優雅的解決方案。 但是當屬性和方法的數量變大時,更好地實現乙個類。

這是乙個簡單的例子,其中閉包可能比定義類和建立物件更為優先。

def make_multiplier_of(n):

def multiplier(x):

return x * n

return multiplier

# multiplier of 3

times3 = make_multiplier_of(3)

# multiplier of 5

times5 = make_multiplier_of(5)

# output: 27

print(times3(9))

# output: 15

print(times5(3))

# output: 30

print(times5(times3(2)))

python中的裝飾器也可以廣泛使用閉包。值得注意的是,可以找到封閉函式中包含的值。

所有函式物件都有乙個__closure__屬性,如果它是乙個閉包函式,它返回乙個單元格物件的元組。 參考上面的例子,我們知道times3和times5是閉包函式。

>>> make_multiplier_of.__closure__

>>> times3.__closure__

單元格(cell)物件具有儲存閉合值的屬性:cell_contents。

>>> times3.__closure__[0].cell_contents

>>> times5.__closure__[0].cell_contents

python 閉包 python 閉包

閉包 因為python中函式也可以當作物件,所以如果出現當我們返回乙個函式,而該函式含有外部變數的時候就形成了閉包。閉包的特點 是個巢狀函式 可以獲得非區域性的變數 將函式當作物件返回 看乙個例子會更易理解 def make printer msg msg hi there def printer ...

python怎麼閉包 Python閉包

python閉包教程 閉包就是乙個 在閉包的記憶功能 在 python 中,獲到閉包中的變數讓閉包本身擁有了記憶效應,閉包中的邏輯可以修改閉包捕獲的變數,變數會跟隨閉包生命期一直存在,閉包本身就如同變數一樣擁有了記憶功能。python閉包定義詳解 語法def func param def func ...

python怎麼閉包 python的閉包

一 思考乙個問題 我們要給定乙個x,要求一條直線上x對應的y的值。公式是y kx b。我們需要用k,b來確定這條直線,則我們實現的函式應該有3個引數 defline k,b,x print k x b line 1,3,4 line 1,3,5 line 1,3,6 可以看到,我們每次修改x都要重新...