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
# 即 在外部函数完成执行之后,我们也可以访问这些变量
应用
- 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__之外只有一个方法- 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.
如果有个全部变量只在一个函数里使用- 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.
隐藏内部函数- To remember a function environment even after it completes its execution: You can then access the variables of this environment later in your program.
获得一个函数执行完成后的变量