Python lambda 与本地值的绑定 [英] Python lambda's binding to local values

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

问题描述

下面的代码吐出1两次,但我希望看到0然后是1.

The following code spits out 1 twice, but I expect to see 0 and then 1.

def pv(v) :
  print v

x = []
for v in range(2):
  x.append(lambda : pv(v))

for xx in x:
  xx()

我希望 python lambdas 在幕后绑定到局部变量指向的引用.然而,情况似乎并非如此.我在一个大型系统中遇到过这个问题,其中 lambda 正在执行现代 C++ 的等效绑定(例如boost::bind"),在这种情况下,您将绑定到智能 ptr 或复制构造 lambda 的副本.

I expected python lambdas to bind to the reference a local variable is pointing to, behind the scenes. However that does not seem to be the case. I have encountered this problem in a large system where the lambda is doing modern C++'s equivalent of a bind ('boost::bind' for example) where in such case you would bind to a smart ptr or copy construct a copy for the lambda.

那么,如何将局部变量绑定到 lambda 函数并使其在使用时保留正确的引用?我对这种行为感到非常震惊,因为我不希望这种带有垃圾收集器的语言会出现这种情况.

So, how do I bind a local variable to a lambda function and have it retain the correct reference when used? I'm quite gobsmacked with the behaviour since I would not expect this from a language with a garbage collector.

推荐答案

x.append(lambda : pv(v)) 更改为 x.append(lambda v=v: pv(v)).

您期望python lambdas 绑定到局部变量指向的引用,在幕后",但这不是 Python 的工作方式.Python 在调用函数时查找变量名,而不是在创建函数时查找.使用默认参数是有效的,因为默认参数是在创建函数时计算的,而不是在调用时计算.

You expect "python lambdas to bind to the reference a local variable is pointing to, behind the scene", but that is not how Python works. Python looks up the variable name at the time the function is called, not when it is created. Using a default argument works because default arguments are evaluated when the function is created, not when it is called.

这并不是 lambda 的特别之处.考虑:

This is not something special about lambdas. Consider:

x = "before foo defined"
def foo():
    print x
x = "after foo was defined"
foo()

印刷品

after foo was defined

这篇关于Python lambda 与本地值的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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