Python 闭包?
programmingpythonserver side programming
在 Python 中,您可以在函数内定义函数,即嵌套函数。Python 闭包是封闭在外部函数内的内部函数。
了解内部函数和外部函数
让我们看一个简单的示例来处理内部函数和外部函数 -
示例
def outerFunc(a): # 封闭函数 def innerFunc(): # 从内部函数访问外部函数的变量 print(a) return innerFunc # 调用封闭函数 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(3) 调用变量 closure1(函数类型)将返回 12,而 closure2(3) 将返回 93。虽然 closure1 和 closure2 都引用同一个函数incrementBy,但我们有两个不同的变量 closure1 和 closure2,它们通过标识符 closureFunc 绑定在一起,导致不同的结果。
__closure__ 属性和单元格对象
使用 __closure__ 属性
要获取更多信息,我们可以使用 __closure__ 属性和单元格对象 −
示例
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