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 = 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")

      GitHubhttps://github.com/fengbingchun/Python_Test

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值