nonloacl pos一定要加,类似globa ,因为在闭包函数里 执行的时候 在 newpo = pos + step 之后定义了 pos = newpo,
所以Python以为我们的pos是函数局部变量,会报错 UnboundLocalError: local variable 'pos' referenced before assignment
这时候我们应该告诉 python pos是我们闭包函数里面的环境变量pos
# *_*coding:utf-8 *_*
"""
意义在于保存一个环境
闭包 = 函数 + 环境 (函数定义时)
"""
"""
旅行者走路
"""
point_x = 0
def tourist(pos):
def go(step):
nonlocal pos
newpo = pos + step
pos = newpo
return newpo
return go
t = tourist(point_x)
print(t(2))
print(t(4))
print(t(6))