def foo():
m = 3
def bar():
print(m) # code 1
m=4 # code 2
bar()
foo()
UnboundLocalError:分配前引用了本地变量'm'
为什么我得到UnboundLocalError
?我知道bar
不能更改m
的值,但是bar
不能仅仅能够获取m
的值吗?
当我分别尝试使用代码1/code 2
时,一切都正常。
答案 0 :(得分:1)
由于内部函数bar
具有赋值m=4
,因此对于整个函数,m
被视为局部变量。但是在您调用print(m)
时,尚未创建m
。因此,您得到错误UnboundLocalError: local variable 'm' referenced before assignment
。
要解决此问题,请声明m
作为全局变量。或避免在bar