Python中的UnboundLocalError: variable referenced before assignment错误分析与解决
来源:互联网 发布:excel表格怎么数据统计 编辑:程序博客网 时间:2024/06/06 09:16
无论python2还是python3中都会出现UnboundLocalError,这个错误由“variable xxx referenced before assignment”得知是由于变量还没有赋值初始化就被引用造成的,如本人在scrapy 中遇到的问题:
yield scrapy.Request(next_url,callback=self.parse)
执行就会报“local variable next_url referenced before assignment”,当然其实我是有初始化的,不过由于程序bug,直接跳过了初始化。
另外值得注意的是,这种情况更多出现的场景是全局变量和局部变量傻傻分不清的情况,在python2和python3中的函数使用变量时都没有默认使用全局变量,所以如果不将变量声明为全局变量的话,就会造成UnboundLocalError错误。如:
count=0def increment(): count=count+1increment()
由于在increment中没有说明count是全局变量,所以默认为局部变量,然而count作为局部变量是没有初始化的,正确的用法如下:
count=0def increment(): global count count=count+1increment()
这样就不存在“local variable referenced before assignment”(局部变量被赋值前即被引用),因为不存在局部变量了,当然如果函数中使用的是局部变量,第一步也是要初始化,这里不再赘言
阅读全文
1 0
- Python中的UnboundLocalError: variable referenced before assignment错误分析与解决
- Python - UnboundLocalError: local variable referenced before assignment
- 错误:UnboundLocalError: local variable 'xxx' referenced before assignment
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- 【Python基础】之全局变量(UnboundLocalError: local variable referenced before assignment)
- 【Python】UnboundLocalError: local variable 'l' referenced before assignment
- 【python】UnboundLocalError: local variable 'counter' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- python:UnboundLocalError: local variable 'l' referenced before assignment
- 【Python】UnboundLocalError: local variable 'x' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- 【Python基础】Python3: UnboundLocalError: local variable 'num' referenced before assignment
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- 【Python异常】UnboundLocalError: local variable 'xxxx' referenced before assignment
- Python 读写当前路径下文件错误 UnboundLocalError: local variable 'file' referenced before assignment
- UnboundLocalError: local variable 'l' referenced before assignment
- UnboundLocalError: local variable 'l' referenced before assignment
- 廖雪峰python 学习日记
- java web 静态资源访问配置
- 数据库——事务
- C语言(21)日期计算
- HYSBZ
- Python中的UnboundLocalError: variable referenced before assignment错误分析与解决
- 减少GC开销的措施
- 关于访问者模式个人总结
- swiper入门小练习-移动端实现上下滑动翻整个页面(一)
- WPF中添加一个文本输入框,按Enter回车,执行绑定的Command
- C# 装箱、拆箱、泛型
- 阿哈磊的挑战11--16
- Mybatis 参数无法获取Parameter not found
- 796B