Python闭包 变量问题

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

原文地址:https://www.cnblogs.com/moonflow/p/2425585.html