栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python3中闭包介绍

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/294165.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号