关于python关闭

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

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


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

查看所有标签

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

Introduction to Algorithms, 3rd Edition

Introduction to Algorithms, 3rd Edition

Thomas H. Cormen、Charles E. Leiserson、Ronald L. Rivest、Clifford Stein / The MIT Press / 2009-7-31 / USD 94.00

Some books on algorithms are rigorous but incomplete; others cover masses of material but lack rigor. Introduction to Algorithms uniquely combines rigor and comprehensiveness. The book covers a broad ......一起来看看 《Introduction to Algorithms, 3rd Edition》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具