内容简介:翻译自:https://stackoverflow.com/questions/11408515/about-python-closure
下面是我从某人关于 python 闭包的博客中得到的一个例子.
我在python 2.7中运行它并获得与我的期望不同的输出.
flist = [] for i in xrange(3): def func(x): return x*i flist.append(func) for f in flist: print f(2)
我的预期输出是:0,2,4
但输出是:4,4,4
有没有人可以帮忙解释一下?
先感谢您.
循环不会在Python中引入范围,因此所有三个函数都关闭相同的i变量,并在循环结束后引用其最终值,即2.
好像几乎每个我在Python上使用闭包的人都被这个问题所困扰.推论是外部函数可以改变我,但内部函数不能(因为这将使我成为局部而不是基于Python的句法规则的闭包).
有两种方法可以解决这个问题:
# avoid closures and use default args which copy on function definition for i in xrange(3): def func(x, i=i): return x*i flist.append(func) # or introduce an extra scope to close the value you want to keep around: for i in xrange(3): def makefunc(i): def func(x): return x*i return func flist.append(makefunc(i)) # the second can be simplified to use a single makefunc(): def makefunc(i): def func(x): return x*i return func for i in xrange(3): flist.append(makefunc(i)) # if your inner function is simple enough, lambda works as well for either option: for i in xrange(3): flist.append(lambda x, i=i: x*i) def makefunc(i): return lambda x: x*i for i in xrange(3): flist.append(makefunc(i))
翻译自:https://stackoverflow.com/questions/11408515/about-python-closure
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Android获取软键盘的高度、键盘的打开与关闭、监听键盘处于打开还是关闭状态
- Swift关闭UITextView键盘
- Android 书本打开和关闭动画
- CentOS 7 关闭透明大页
- Oracle数据库启动和关闭
- Oracle连接启动和关闭模式(汇总)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Visual Thinking
Colin Ware / Morgan Kaufmann / 2008-4-18 / USD 49.95
Increasingly, designers need to present information in ways that aid their audiences thinking process. Fortunately, results from the relatively new science of human visual perception provide valuable ......一起来看看 《Visual Thinking》 这本书的介绍吧!