【发布时间】:2024-01-06 02:57:01
【问题描述】:
在 Python 2.7 中,运行以下代码:
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()
我得到不同的错误:
Traceback (most recent call last):
File "test.py", line 4, in <module>
f()
File "test.py", line 2, in f
a[0] = a[0] + 1
NameError: global name 'a' is not defined
为什么当a 是int 时,Python 认为a 是局部变量,而当list 时是全局变量?这背后的原理是什么?
P.S.:我在阅读 this thread 后进行实验。
【问题讨论】:
标签: python scope global-variables