为什么我在写 python 闭包时遇到 UnboundLocalError,而在另一个类似的代码片段中却没有?

Why I encounter an UnboundLocalError when I wrote a python closure, but in another similar code snippet I didn't?

我这里有两个代码片段。

第一个,函数创建

def creat(pos):
  
  def move(direction, step):
    new_x = pos[0] + direction[0]*step
    new_y = pos[1] + direction[1]*step
    pos[0] = new_x
    pos[1] = new_y

    return pos
  
  return move


player = creat([0,0])
print('after move along x 5 step, the new position is:'+str(player([1,0], 5)))
print('after move along y 10 step, the new position is:'+str(player([0,1], 10)))

第二个,函数包装器

def wrapper(x):
  def func():
    temp = x+1
    x = temp
    return x
  return func

counter = wrapper(0)
for i in range(5):
  print(counter())

第一个运行良好,但第二个引发有关变量 x 的错误:局部变量 x 在赋值前被引用。我可以从字面上理解这个错误的意思,但我认为变量 x 应该与前一个片段中的变量 pos 相同。为什么 pos 可以,但 x 不行?

赋值 x = temp 创建了一个新的局部变量,它隐藏了 wrapper 定义的 non-local x。即使 temp = x + 1运行 时间 之前,它仍然引用尚未初始化的局部变量 x