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

Python 闭包 Closures

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

Python 闭包 Closures

Python Closures are these inner functions that are enclosed within the outer function. Closures can access variables present in the outer function scope. It can access these variables even after the outer function has completed its execution.
Python闭包是那些封闭在外部函数中的内部函数。闭包可以访问存在于外部函数作用域中的变量。即使在外部函数完成执行之后,它也可以访问这些变量。

python 嵌套函数中的作用域是如何工作的
def outer(name):
    # 外部函数(enclosing function)

    def inner():
        # 内部函数(enclosed function)

        # 内部函数访问外部函数 name 变量
        print(name)

    inner()

# 调用外部函数
outer('Soapcmd')
# Output:
# Soapcmd

# 即: 闭包可以访问存在于外部函数作用域中的变量

python 闭包

The inner function becomes a closure when we return the inner function instead of calling it
返回内部函数而不是直接执行它,则内部函数就会成为一个闭包

So we have a closure in Python if

We have a nested function, i.e. function within a function
The nested function refers to a variable of the outer function
The enclosing function returns the enclosed function
闭包的三个条件:
嵌套函数
内部函数访问外部函数的变量
外部函数返回内部函数

def outer(name):
    # 外部函数(enclosing function)

    def inner():
        # 内部函数(enclosed function)

        # 内部函数访问外部函数 name 变量
        print(name)

    return inner # 这里直接返回而非调用

# 调用外部函数
myFunction = outer('Soapcmd') # 外部函数已执行完毕
myFunction() # name变量依然被记住
# Output:
# Soapcmd

# 即 在外部函数完成执行之后,我们也可以访问这些变量
应用
  1. To replace the unnecessary use of class: Suppose you have a class that contains just one method besides the init method. In such cases, it is often more elegant to use a closure instead of a class.
    如果一个class除__init__之外只有一个方法
  2. To avoid the use of the global scope: If you have global variables which only one function in your program will use, think closure. Define the variables in the outer function and use them in the inner function.
    如果有个全部变量只在一个函数里使用
  3. To implement data hiding: The only way to access the enclosed function is by calling the enclosing function. There is no way to access the inner function directly.
    隐藏内部函数
  4. To remember a function environment even after it completes its execution: You can then access the variables of this environment later in your program.
    获得一个函数执行完成后的变量
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1009497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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