我这里有两个代码片段。
第一个,函数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
不行?