function newCounter() | |
local i = 0 | |
return function() -- anonymous function | |
i = i + 1 | |
return i | |
end | |
end | |
c1 = newCounter() | |
print(c1()) --> 1 | |
print(c1()) --> 2 |
def new_counter(): | |
i = [0] | |
def nested(): | |
i[0] += 1 | |
return i[0] | |
return nested | |
>>>c = new_counter() | |
>>>c() | |
1 | |
>>>c() | |
2 |
def new_counter(): | |
i = 0 | |
def nested(): | |
i += 1 | |
return i | |
return nested | |
c = new_counter() | |
c() | |
--------------------------------------------------------------------------- | |
UnboundLocalError Traceback (most recent call last) | |
<ipython-input-3-1f2bdb17cf98> in <module>() | |
----> 1 c() | |
<ipython-input-1-6662aa87dc2a> in nested() | |
2 i = 0 | |
3 def nested(): | |
----> 4 i += 1 | |
5 return i | |
6 return nested | |
UnboundLocalError: local variable 'i' referenced before assignment |
![]() |
1
monsterxx03 2014-04-08 23:47:00 +08:00 ![]() python闭包的经典问题
i+=1 等价于i = i + 1, 语句从左向右执行,先是`i=`, 注意这里就覆盖了外部的i,实际上外部的i已经不可见了,然后`i+1`, 但此时外部的i在当前作用域中已经不可见,内部的i还未创建完成,等号右边的还没执行完成呢。。。所以会找不到这个i。 lua能过,应该是语法解释器内部的逻辑和python不一样吧。 |
![]() |
2
wenLiangcan OP @monsterxx03 那为什么列表又不会被覆盖呢?
|
![]() |
3
monsterxx03 2014-04-09 00:04:55 +08:00
因为 i= xxx是在定义变量, i[0] =xxx 不是定义,只是赋值操作。
|
![]() |
4
wenLiangcan OP @monsterxx03 原来如此!
|
![]() |
5
josephok 2014-04-12 16:10:23 +08:00
试试:
<script src="https://gist.github.com/josephok/10524138.js"></script> |
![]() |
6
josephok 2014-04-12 16:12:08 +08:00 ![]() |
![]() |
7
wenLiangcan OP @josephok 原来还有 nonlocal 这个关键字,学习了,v2ex 竟然没有提醒,现在才看到。。。
|