关于python关闭

栏目: Python · 发布时间: 5年前

内容简介:翻译自: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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Visual Thinking

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》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具