python - Python UnboundLocalError,是什么原因造成的?
问题描述
在python中我写道:
registered_to = 0
def execute_data():
registered_to += response.text.count("<div class=\"info-msg\">")
但我得到:
registered_to += response.text.count("<div class=\"info-msg\">")
UnboundLocalError: local variable 'registered_to' referenced before assignment
解决方案
这是你想要的吗?
registered_to = 0
def execute_data():
global registered_to
registered_to += response.text.count("<div class=\"info-msg\">")
每当您希望从非全局范围(如函数)修改/创建全局变量时,都必须使用global关键字。如果您只是使用非全局范围内的全局变量而不修改它,则无需使用关键字。
例子
- 在非全局范围内使用全局变量但不修改它
wish = "Hello "
def fun():
print(wish)
fun()
- 在非全局范围内使用全局变量并对其进行修改
wish = "Hello "
def fun():
word += "World"
print(wish)
fun()
推荐阅读
- json - 在不知道属性位置的情况下查询给定属性的 JSON
- javascript - 在什么情况下不会到达 finally 块?
- powershell - 比较单个 PowerShell 数组中的对象
- firebase - 何时必须在 firestore 触发函数中执行 firestore 读取和写入操作或在 api 端点中直接调用 firestore 之间进行选择
- c# - 尝试使用 COM-interop 从 C# 库中附加 vb6 中的对象时,获取“无法将 'Field' 转换为 'Field' 类型(同一类)”
- asp.net-mvc - IIS 默认网站的 ASP.NET Core 3.1 MVC 路由问题
- azure - AD FS 配置
- vuejs2 - 如何摆脱 NuxtJs 中不匹配的 childNodes 与 VNodes
- redux - 是否可以在执行异步操作的类中保留 redux 调度功能?
- reactjs - 在 React 中,第一次出现在页面上时以不同方式呈现组件的最佳方式是什么?