Python3中闭包介绍
生活随笔
收集整理的這篇文章主要介紹了
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中闭包介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3中global/nonlo
- 下一篇: Python3中__init__.py文