Why do I get a quot;referenced before assignmentquot; error when assigning to a global variable in a function?(为函数中的全局变量赋值时,为什么在赋值quot;之前引用了quot;错误?)
本文介绍了为函数中的全局变量赋值时,为什么在赋值";之前引用了";错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我收到以下错误:
UnboundLocalError: local variable 'total' referenced before assignment
在文件的开头(在错误所在的函数之前),我使用global
关键字声明total
。然后,在程序体中,在调用使用total
的函数之前,我将其赋值为0。我已尝试在不同位置(包括声明之后的文件顶部)将其设置为0,但无法使其正常工作。
有人看到我做错了什么吗?
推荐答案
我认为您错误地使用了"GLOBAL"。请参见Python reference。您应该声明不带GLOBAL的变量,然后在函数内部,当您想要访问全局变量时,您可以声明它global yourvar
。
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
请参见此示例:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
因为doA()
不修改全局合计,所以输出为%1而不是%11。
这篇关于为函数中的全局变量赋值时,为什么在赋值";之前引用了";错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:为函数中的全局变量赋值时,为什么在赋值";之前引用了";错误?


猜你喜欢
- 沿轴计算直方图 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01