有一个python闭包函数:
def test(a):
def delete():
print "first", a
delete()
print "second", a
test(1)
输出是:
first 1
second 1
然后我们尝试另一个功能:
def test(a):
def delete():
print "first", a
del a
delete()
print "second", a
test(1)
我们得到了输出:
UnboundLocalError
Traceback (most recent call last)
<ipython-input-28-c61f724ccdbf> in <module>()
6 print "second", a
7
----> 8 test(1)
<ipython-input-28-c61f724ccdbf> in test(a)
3 print "first", a
4 del a
----> 5 delete()
6 print "second", a
7
<ipython-input-28-c61f724ccdbf> in delete()
1 def test(a):
2 def delete():
----> 3 print "first", a
4 del a
5 delete()
UnboundLocalError: local variable 'a' referenced before assignment
为什么变量 a 在 del 之前变为局部变量?
请注意错误在行
print "first", a
但不是
del a
答案 0 :(得分:1)
名称a
是test()
范围的本地名称,但不属于delete()
的范围。
由于您尝试del a
,因此Python 假设 a
是本地的,而不是。{/ p>
最后,您在print "first", a
上收到错误,因为假设a是本地但在此之前打印之前未定义。