以下代码在Python 2.5和3.0中按预期工作:
a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
Run Code Online (Sandbox Code Playgroud)
但是,当我取消注释行(B)时,我得到了UnboundLocalError: 'c' not assigned一行(A).的值a和b被正确地打印.这让我感到困惑,原因有两个:
为什么在行(A)处抛出运行时错误,因为后面的行(B)语句?
为什么变量a和b打印符合预期,同时c引发错误?
我能想到的唯一解释是,赋值创建了一个局部变量,即使在创建局部变量之前,它也优先于"全局"变量.当然,变量在存在之前"窃取"范围是没有意义的.cc+=1c
有人可以解释一下这种行为吗?
第一个代码片段打印[0, 3]出来。
def func():
a = [0]
def swim():
a.append(3)
# a = [1]+a
return a
return swim()
print(func())
Run Code Online (Sandbox Code Playgroud)
第二个代码片段引发错误“UnboundLocalError:赋值前引用的局部变量‘a’”
def func():
a = [0]
def swim():
# a.append(3)
a = [1]+a
return a
return swim()
print(func())
Run Code Online (Sandbox Code Playgroud)
到底a功能是否可见/可访问?swim
我认为list.extend列表中的"+ ="基本上做同样的事情 - 扩展列表而不创建新列表.
我希望下面的代码可以打印,[42, 43, 44, 45, 46]但我得到了UnboundLocalError: local variable 'x' referenced before assignment
为什么我收到此错误?区别在哪里?
def f():
x.extend([43, 44])
def g():
x += ([45, 46])
x = [42]
f()
g()
print x
Run Code Online (Sandbox Code Playgroud)
我在python2.7.3和python3.4.0中尝试过这个.