python 3.11+ · Python
报错原文
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
这是什么意思
只要函数体里任何一处给这个名字赋了值,Python 就把它当作函数的局部变量——而你在赋值执行之前就读了它。当你期望读到外层同名的值时,或者第一次写 count += 1 这类先读后写的运算时,就会碰到。通常的答案是在函数里先 count = 0;如果确实要改模块级的值,global count 能做到,代价是这个值由谁改写变得难以追踪。3.10 之前同一个错误写作 'local variable referenced before assignment'。
怎么修
这个没有一行命令能解决。说明里写了该看哪里。
- 来自
- python 3.11+
- Python
- 18
Python 的 traceback 把答案劈成两半——最后一行说「错了什么」,上面的帧说「错在哪里」——所以只读最后一行,你会拿到名字却丢掉位置;而 NoneType、KeyError 这类「值不存在」的错误,原因几乎总在崩溃那一帧的上面。
怎么读报错
- 从第一行往下读。越往下越是工具内部的事,起因通常写在最上面。
- 有文件名和行号就从那里查——不是栈顶那一帧,而是最上面那条提到你自己写的文件的行。
- 把报错原文照样去搜,但先去掉你自己的路径和变量名,正是那些让搜索匹配不上。
- 同一种情况在不同版本里措辞不同。结果不对头,就把版本号一起加进查询。
- 粘贴修法之前,先确认它会丢掉什么。这里面有些是不能撤回的。
常见问题
Q. “UnboundLocalError: cannot access local variable 'count' where it is not associated with a value” 是什么意思?
只要函数体里任何一处给这个名字赋了值,Python 就把它当作函数的局部变量——而你在赋值执行之前就读了它。当你期望读到外层同名的值时,或者第一次写 count += 1 这类先读后写的运算时,就会碰到。通常的答案是在函数里先 count = 0;如果确实要改模块级的值,global count 能做到,代价是这个值由谁改写变得难以追踪。3.10 之前同一个错误写作 'local variable referenced before assignment'。
Q. 怎么修?
没有一行命令能解决。上面的说明写了该看哪里。
Q. 这是哪个工具报的?
python 3.11+。它属于Python,报错原文有 14 个词。
相关报错
AttributeError: 'NoneType' object has no attribute 'get'pythonTypeError: greet() takes 1 positional argument but 2 were givenpythonPermissionError: [Errno 13] Permission deniedpythonOSError: [Errno 98] Address already in usepythonModuleNotFoundError: No module named 'requests'pythonerror: externally-managed-environmentpip 23+ImportError: cannot import name 'User' from partially initialized module 'models' (most likely due to a circular import)pythonIndentationError: unexpected indentpython