我正在使用Python2.7,仍然对python的作用域很困惑。我无法解释为什么会发生这种情况。有人可以帮我。提前谢谢。
案例1:
x = 1
def func():
print x
func()
=> result:
1
案例2:
x = 1
def func():
print x
x = 9
func()
=>结果:
UnboundLocalError: local variable 'x' referenced before assignment
当我在case 2中添加x = 9
行时,出现错误。
如果您在方法中重新分配外部变量,您应该使用global:
x = 1
def func():
global x
print x
x = 9
func()
在可变变量(如list或dict)的情况下,当您只需要修改内部状态(list。添加、列表。pop) -你不需要global关键字