Python3中闭包介绍

2022-10-11 13:06:49

      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 = 3

if var == 1:
    # reference: https://www.geeksforgeeks.org/python-closures/
    def outerFunction(text):
        text = text

        def innerFunction():
            print(text)

        # Note we are returning function WITHOUT parenthesis(括号)
        return innerFunction

    myFunction = 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_func

    def add(x, y):
        return x+y

    add_logger = logger(add)
    add_logger(3, 3)
elif var == 3:
    # reference: https://data-flair.training/blogs/python-closure/
    def outer(x):
        result=0

        def inner(n):
            nonlocal result
            while n>0:
                result+=x*n
                n-=1
            return result # 7*3 + 7*2 + 7 = 42

        return inner

    myfunc=outer(7)
    print(myfunc(3)) # 42

print("test finish")

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

  • 作者:fengbingchun
  • 原文链接:https://blog.csdn.net/fengbingchun/article/details/120616259
    更新时间:2022-10-11 13:06:49