Python 闭包
在Python中,您可以在函数内定义函数,即嵌套函数。Python的闭包就是这些嵌套在外部函数中的内部函数。
理解内部函数和外部函数
让我们看一个简单的示例来理解内部函数和外部函数的工作方式−
示例
def outerFunc(a):
# the enclosing function
def innerFunc():
# accessing outer function’s variable from inner function
print(a)
return innerFunc
# calling the enclosing function
demoFunc = outerFunc('Hello')
demoFunc()
输出
Hello
为了理解Python闭包,首先让我们了解什么是嵌套函数和Python类。
Python嵌套函数
在另一个函数内部定义的函数称为嵌套函数。嵌套函数可以访问封闭作用域的变量。让我们看一个示例 –
示例
def funcOut():
print("This is outer function.")
def funcIn():
print("This function is defined inside funcOut. \nThis function(funcIn) is called\ nested function.")
print("We can call nested function here.")
funcIn()
print("We are in outer function.\nCalling funcOut.")
funcOut()
输出
We are in outer function.
Calling funcOut.
This is outer function.
We can call nested function here.
This function is defined inside funcOut.
This function(funcIn) is callednested function.
因此,funcIn是定义在funcOut内部的嵌套函数。通过查看上面的输出,我们可以了解函数的调用顺序。如果我们希望从funcOut获得funcIn的所有功能,则必须在上述程序中执行“return funcIn”,这称为Python中的闭包。简而言之,闭包是一个记住其创建环境(封闭作用域)的函数(对象)。
示例
def closureFunc(start):
def incrementBy(inc):
return start + inc
return incrementBy
closure1 = closureFunc(9)
closure2 = closureFunc(90)
print ('clsure1(3) = %s' %(closure1(3)))
print ('closure2(3) = %s' %(closure2(3)))
输出
clsure1(3) = 12
closure2(3) = 93
调用函数类型的变量closure1(closure1(3))将返回12,而调用closure2(3)将返回93。尽管closure1和closure2都引用同一个函数incrementBy,但我们有两个不同的变量closure1和closure2,它们通过标识符closureFunc绑定在一起,导致了不同的结果。
__closure__ attribute and cell objects
使用__closure__
属性
我们可以使用__closure__
属性和cell对象来获取更多信息。
示例
def closureFunc(start):
def incrementBy(inc):
return start + inc
return incrementBy
a= closureFunc(9)
b = closureFunc(90)
print ('type(a)=%s' %(type(a)))
print ('a.__closure__=%s' %(a.__closure__))
print ('type(a.__closure__[0])=%s' %(type(a.__closure__[0])))
print ('a.__closure__[0].cell_contents=%s' %(a.__closure__[0].cell_contents))
print ('type(b)=%s' %(type(b)))
print ('b.__closure__=%s' %(b.__closure__))
print ('type(b.__closure__[0])=%s' %(type(b.__closure__[0])))
print ('b.__closure__[0].cell_contents=%s' %(b.__closure__[0].cell_contents))
输出
type(a)=<class 'function'>
a.__closure__=<cell at 0x7efdfb4683a8: int object at 0x7efdfc7324c0>
type(a.__closure__[0])=<class 'cell'>
a.__closure__[0].cell_contents=9
type(b)=<class 'function'>
b.__closure__=<cell at 0x7efdfb3f9888: int object at 0x7efdfc732ee0>
type(b.__closure__[0])=<class 'cell'>
b.__closure__[0].cell_contents=90