为什么del会为参数生成UnboundLocalError?

时间:2017-08-23 14:24:02

标签: python del

有一个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

1 个答案:

答案 0 :(得分:1)

名称atest()范围的本地名称,但不属于delete()的范围。

由于您尝试del a,因此Python 假设 a是本地的,而不是。{/ p>

最后,您在print "first", a上收到错误,因为假设a是本地但在此之前打印之前未定义。