Python 闭包
在Python中,__closure__
是一个用于获取函数闭包(closure)的属性。闭包是指函数对象和引用该函数定义时的环境(即自由变量)的组合。
当一个嵌套函数引用了外部函数的变量时,就会创建一个闭包。__closure__
属性返回一个包含引用的自由变量的元组,或者如果函数没有闭包,返回 None
。
def sqrt():
x = 1
def f(y):
nonlocal x
x += y
return x
return f
def sqrt2():
x = [1]
def f(y):
# nonlocal x
x[0] += y
return x
return f
s = sqrt()
print(s(1))
print(s(1))
print(s(1))
print(s(1))
print(s(1))
print(s(1))
print(s.__closure__)
for i in s.__closure__:
print(i.cell_contents)
输出:
2
3
4
5
6
7
(<cell at 0x000001C6893ACFD0: int object at 0x000001C6E78969F0>,)
7