python - “UnboundLocalError:分配前引用的局部变量”使用全局变量后
问题描述
我正在尝试访问我已经尝试过使其成为全局的函数中的变量,但这不起作用。这是我的代码(精简后没有不必要的变量声明):
global col
col = 0
def interpret(text):
for char in text:
col += 1
我得到的错误说:
Traceback (most recent call last):
File "main.py", line 156, in <module>
interpret(line) (Where I call the function in the rest of the code)
File "main.py", line 21 (5), in interpret
col += 1
UnboundLocalError: local variable 'col' referenced before assignment
我怎样才能解决这个问题?
解决方案
您需要global
在函数中包含以下语句:
col = 0
def interpret(text):
global col
for char in text:
col += 1
在函数外部赋值col
会创建变量,但为了能够在函数内部写入,global
语句需要在每个函数内部。
顺便说一句,作为一名程序员,您应该非常非常非常努力地不使用全局变量。
您应该将变量传递给函数以供它们操作:
col = 0
def interpret(text, cnt):
for char in text:
cnt += 1
return cnt
text = ...
col = interpret(text, col) # pass col in and assign it upon return.
推荐阅读
- typo3 - 如果请求了无效的类型号/typeNum,则回退到默认的 TYPO3 页面类型
- progressive-web-apps - PWA(渐进式网络应用程序)不能在桌面上以全屏模式工作?
- scala - 是否可以在自定义序列化程序中序列化为已知的默认格式?
- vim - 如何找到在正常模式下插入字符的 VimL 函数?
- mesos - 带资源标志的 Mesos 代理内存控制
- java - 在将相同的元素添加到新的 ArrayList 后,有什么方法可以从给定的 ArrayList 中删除一些元素?
- php - 从表中选择,其中列是 PHP 中的外键
- html - 如何在 Laravel 中上传文件?
- php - yii2 身份 $authKey 返回数组
- sql - 如何使用 SQL 将一个表中的列与另一个值进行比较