admin管理员组文章数量:1288019
In JS, we can write closure like:
function f(){
var a=0;
function g(){
alert(a++);
}
return g;
}
g=f()
g()
However, if I write following code in python
def f():
a=0
def g():
a+=1
print a
return g
g=f()
g()
Then I get UnboundedLocalError.
Can anyone tell me the difference between closure in python and JS?
In JS, we can write closure like:
function f(){
var a=0;
function g(){
alert(a++);
}
return g;
}
g=f()
g()
However, if I write following code in python
def f():
a=0
def g():
a+=1
print a
return g
g=f()
g()
Then I get UnboundedLocalError.
Can anyone tell me the difference between closure in python and JS?
Share Improve this question edited May 6, 2011 at 10:40 Ikke 101k23 gold badges100 silver badges120 bronze badges asked May 6, 2011 at 10:37 user607722user607722 1,6862 gold badges13 silver badges22 bronze badges 2- 3 Do you really believe that this difference will explain what you're seeing? – Ignacio Vazquez-Abrams Commented May 6, 2011 at 10:38
- I think so. Direct explanation of the observed result is also wele – user607722 Commented May 6, 2011 at 16:10
2 Answers
Reset to default 12When you use a += 1
in Python it refers to a local (uninitialized) variable in scope of g
function. Basically you can read variables from upper scopes, but if you try to write it will refer to a variable in most recent scope. To make it work like you want you have to use nonlocal
keyword that is only present Python 3. In Python 2 you can't do that as far as I know, unless the variable you're trying to change is is global, then global
keyword es to the rescue.
def f():
a=0
def g():
nonlocal a
a+=1
print a
return g
g=f()
g()
Version for python 2:
def f():
a=0
def g():
g.a+=1
print g.a
g.a=a
return g
g=f()
g()
本文标签: Difference between closures in python and javascriptStack Overflow
版权声明:本文标题:Difference between closures in python and javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741335106a2372995.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论