常见的local variable 'x' referenced before assignment问题
来源:互联网 发布:mac os系统在哪下载 编辑:程序博客网 时间:2024/05/21 10:10
def fun1(): x = 5 def fun2(): x *= 2 return x return fun2()
如上代码,调用fun1()
运行会出错:UnboundLocalError: local variable 'x' referenced before assignment。
这是因为对于fun1函数,x是局部变量,对于fun2函数,x是非全局的外部变量。当在fun2中对x进行修改时,会将x视为fun2的局部变量,屏蔽掉fun1中对x的定义;如果仅仅在fun2中对x进行读取,则不会出现这个错误。
解决办法:使用nonlocal关键字
def fun1(): x = 5 def fun2(): nonlocal x x *= 2 return x return fun2()fun1()Out[14]: 10
使用了nonlocal x后,在fun2()中就不再将x视为fun2的内部变量,fun1函数中对x的定义就不会被屏蔽掉。
阅读全文
0 0
- 常见的local variable 'x' referenced before assignment问题
- 【Python】UnboundLocalError: local variable 'x' referenced before assignment
- 关于 local variable 'has' referenced before assignment 问题
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- Python的UnboundLocalError: local variable 'xxx' referenced before assignment
- local variable 'xxx' referenced before assignment
- Python - UnboundLocalError: local variable referenced before assignment
- UnboundLocalError: local variable 'l' referenced before assignment
- UnboundLocalError: local variable 'l' referenced before assignment
- local variable 'xxx' referenced before assignment
- UnboundLocalError: local variable ' ' referenced before assignment
- local variable 'a' referenced before assignment
- python - Local variable referenced before assignment
- local variable 'xxx' referenced before assignment
- local variable 'xxx' referenced before assignment
- local variable 'xxx' referenced before assignment
- 几种常用范数与距离的关系
- 基于Qt的进程类QProcess启动本地Chrome浏览器
- luogu P1019 单词接龙 【dfs】
- uva 10641
- 大小写字母的转换
- 常见的local variable 'x' referenced before assignment问题
- 【案例分享】唯品会海量实时OLAP分析技术升级之路
- [Oracle 11g r2(11.2.0.4.0)]集群守护进程gpnp介绍
- 个人如何发表论文
- 微信购物直播商城渠道定制开发
- LINUX中常用操作命令
- Eclipse Problems During Content Assist正确解决方法
- 顺序表应用 有序顺序表 归并
- 20171014Redis学习总结