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/archive/2012/03/30/2425585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值