在Python 2.7,运行下面的代码:Python的全局和局部变量
def f():
a = a + 1
f()
给出以下结果:
Traceback (most recent call last):
File "test.py", line 4, in <module>
f()
File "test.py", line 2, in f
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
但是,如果我的代码更改为以下:
def f():
a[0] = a[0] + 1
f()
我得到了不同的错误:
为什么Python考虑a
是一个局部变量,当它是一个int
,全局是list
?这背后的理由是什么?
P.S .:我在阅读this thread后进行了实验。
我认为这个错误与g中的赋值无关。我编辑了删除无关语句的问题。 – fossilet 2013-03-24 03:52:00
@fossilet - 道歉,我误以为你的问题 - 我更新了我的答案,让我知道它是否有帮助。 – 2013-03-24 04:39:30