闭包 = 函数 + 环境变量
实例:
def curve_pre():
a = 25
def curve(x):
return a * x * x
return curve
a = 10
f = curve_pre()
print(f.__closure__) # (<cell at 0x0000000002595BE8: int object at 0x000007FED8E77400>,)
print(f.__closure__[0].cell_contents) # 25 查看环境变量 验证是否是闭包
print(f(2)) # 100
global 把局部变量转换成全局变量
nonlocal 声明变量不是局部变量
实例:
origin = 0
def position(pos):
def go(step):
nonlocal pos
new_pos = pos + step
pos = new_pos
return new_pos
return go
t = position(origin)
print(t(2)) # 2
print(t(3)) # 5
print(t(5)) # 10
有记忆现场的功能