日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Python3中闭包介绍

發布時間:2023/11/27 生活经验 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python3中闭包介绍 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? Python3中的閉包(closure)是一個函數對象,它記住封閉作用域(enclosing function)中的值,即使它們不存在于內存中。它是一個將函數與環境一起存儲的記錄。由于閉包用作回調函數,因此它們提供了某種數據隱藏,這有助于我們減少使用全局變量。

? ? ? Python3中的嵌套函數(nested function):在另一個函數中定義一個函數,內部函數(inner function)能夠訪問封閉范圍內(外部函數, outer function)的變量。

? ? ? Python3中的閉包必須滿足三個條件:

? ? ? (1). 必須有一個嵌套函數。

? ? ? (2). 這個嵌套函數必須引用一個非本地(nonlocal)變量(一個在它封閉的范圍內的變量)。

? ? ? (3). 封閉作用域必須返回內部函數。

? ? ? 以上內容主要參考:

? ? ? 1. https://www.geeksforgeeks.org/python-closures/

? ? ? 2.?https://data-flair.training/blogs/python-closure/

? ? ? 以下為測試代碼:

var = 3if var == 1:# reference: https://www.geeksforgeeks.org/python-closures/def outerFunction(text):text = textdef innerFunction():print(text)# Note we are returning function WITHOUT parenthesis(括號)return innerFunctionmyFunction = outerFunction('Hey!')myFunction()
elif var == 2:# reference: https://www.geeksforgeeks.org/python-closures/def logger(func):def log_func(*args):print(func(*args))# Necessary for closure to work(returning WITHOUT parenthesis)return log_funcdef add(x, y):return x+yadd_logger = logger(add)add_logger(3, 3)
elif var == 3:# reference: https://data-flair.training/blogs/python-closure/def outer(x):result=0def inner(n):nonlocal resultwhile n>0:result+=x*nn-=1return result # 7*3 + 7*2 + 7 = 42return innermyfunc=outer(7)print(myfunc(3)) # 42print("test finish")

? ? ? GitHub:?https://github.com/fengbingchun/Python_Test

總結

以上是生活随笔為你收集整理的Python3中闭包介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。