您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: