Python中的词法闭包 [英] Lexical closures in Python

查看:126
本文介绍了Python中的词法闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调查一个问题,我用JavaScript代码中的词法闭包,我在Python中遇到这个问题:

While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:

flist = []

for i in xrange(3):
    def func(x): return x * i
    flist.append(func)

for f in flist:
    print f(2)

请注意,避免 lambda 。它打印4 4 4,这是惊人的。我希望0 2 4。

Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".

这个等价的Perl代码是正确的:

This equivalent Perl code does it right:

my @flist = ();

foreach my $i (0 .. 2)
{
    push(@flist, sub {$i * $_[0]});
}

foreach my $f (@flist)
{
    print $f->(2), "\n";
}

打印0 2 4。

您能解释一下吗?

更新:

问题不是 i 是全局性的。这显示相同的行为:

The problem is not with i being global. This displays the same behavior:

flist = []

def outer():
    for i in xrange(3):
        def inner(x): return x * i
        flist.append(inner)

outer()
#~ print i   # commented because it causes an error

for f in flist:
    print f(2)

如注释行所示, i 在该点未知。仍然,它打印4 4 4。

As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".

推荐答案

Python实际上是定义。 创建了三个独立的函数,但它们各自具有它们在中定义的环境的闭包 - 在这种情况下是全局环境(或外部函数的环境,如果循环放置在另一个函数内部)。这正是问题,虽然 - 在这种环境下, i是变异,并且所有都指向同一个

Python is actually behaving as defined. Three separate functions are created, but they each have the closure of the environment they're defined in - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, i is mutated, and the closures all refer to the same i.

这里是最好的解决方案,我可以想出 - 创建一个函数creater并调用 。这将对每个创建的函数强制使用不同的环境,每个函数使用不同的i

Here is the best solution I can come up with - create a function creater and invoke that instead. This will force different environments for each of the functions created, with a different i in each one.

flist = []

for i in xrange(3):
    def funcC(j):
        def func(x): return x * j
        return func
    flist.append(funcC(i))

for f in flist:
    print f(2)

这是当你混合副作用和功能编程时会发生什么。

This is what happens when you mix side effects and functional programming.

这篇关于Python中的词法闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆