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.
    获得一个函数执行完成后的变量
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值