" UnboundLocalError"报告错误的行号

时间:2017-07-26 08:40:52

标签: python

例如:

$ cat -n foo.py
     1  def f():
     2      str = len
     3      str = str('abc')
     4  #   len = len('abc')
     5  f()
$ python2.7 foo.py
$

它成功运行,因此第2行和第3行没有问题。但在我取消注释第4行之后:

$ cat -n bar.py
     1  def f():
     2      str = len
     3      str = str('abc')
     4      len = len('abc')
     5  f()
$ python2.7 bar.py
Traceback (most recent call last):
  File "bar.py", line 5, in <module>
    f()
  File "bar.py", line 2, in f
    str = len
UnboundLocalError: local variable 'len' referenced before assignment
$

现在它报告错误,因此未注释的第4行肯定有问题,但为什么第2行报告了回溯错误?

2 个答案:

答案 0 :(得分:2)

编程常见问题解答中有一个答案

  

这是因为当您对作用域中的变量进行赋值时,   该变量变为该范围的局部变量并且类似地影响任何变量   外部范围内的命名变量。

在此处阅读完整内容:Why am I getting an UnboundLocalError when the variable has a value?

当注释len时,它被视为函数len()

中的构建
def f():
    str = len
    print type(str)
    str = str('abc')
    # len = len('abc')
    print type(len)

f()

<type 'builtin_function_or_method'>
<type 'builtin_function_or_method'>

答案 1 :(得分:0)

在L4评论中,len被解析为函数len()

取消注释L4后,len被解析为局部变量。