gpt4 book ai didi

python - "UnboundLocalError"报告错误的行号

转载 作者:行者123 更新时间:2023-12-01 02:45:12 24 4
gpt4 key购买 nike

例如:

$ 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 行报告回溯错误?

最佳答案

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

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.

在此处阅读完整内容: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'>

关于python - "UnboundLocalError"报告错误的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45321689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com