0

我这里有两个代码片段。

第一个,函数create

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不行?

4

1 回答 1

1

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

于 2020-11-02T15:10:38.893 回答