Python闭包 变量问题
2012-03-30 16:36
239 查看
def getadd(): count=[0] def incr(x): count[0]+=x print(count[0]) return incr a=getadd() a(1) def getadd(): count=0 def incr(x): count+=x print(count) return incr a=getadd() a(1)
为什么第二段代码不能成功执行,会说'count' referenced before
assignment,但是第一段以列表的形式就没有问题呢?请大家指点
第二段中的 count+=x 表达式是一个赋值表达式,这会创建一个本地的count变
量,但是此表达式中又需要引用count,即count = count + x,这就是错误的由来
第一段中对count仅仅是引用,没有赋值操作,count[0]+=x 是赋值给count的第一
个元素,该元素已经存在,没有错误
http://groups.google.com/group/python-cn/browse_thread/thread/b994e99cb980bd08?hl=en
相关文章推荐
- 一个Python中的闭包问题
- 浅析Python多线程下的变量问题
- python--多线程编程中的线程间通信的问题--变量同步锁
- 关于python的环境变量问题
- [python]变量作用域问题
- python全局变量被覆盖的问题
- Python在函数中使用全局变量的问题
- 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment 分类: divide into python python基础学习 问题总结 2014-01-01 16:35 4595人阅读 评论(0)
- 解析Python中的变量、引用、拷贝和作用域的问题
- python中将函数赋值给变量时需要注意的一些问题
- 关于 私有变量的访问问题【 java python]
- 实例讲解Python的函数闭包使用中应注意的问题
- 在crontab中执行python脚本系统环境变量问题
- [Python]变量作用域问题UnboundLocalError
- 深入探究Python中变量的拷贝和作用域问题
- [Python爬虫] 中文编码问题:raw_input输入、文件读取、变量比较等str、unicode、utf-8转换问题
- python 本地变量和全局变量 locals() globals() global nonlocal 闭包 以及和 scala 闭包的区别
- Python学习(21):Python函数(5):变量作用域与闭包
- 实例讲解Python的函数闭包使用中应注意的问题
- python中闭包中变量的影响因素