循环中的 Lambda [英] Lambda in a loop

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

问题描述

考虑以下代码片段:

# directorys == {'login': <object at ...>, 'home': <object at ...>}
for d in directorys:
    self.command["cd " + d] = (lambda : self.root.change_directory(d))

我希望创建一个包含两个函数的字典,如下所示:

I expect to create a dictionary of two function as following :

# Expected :
self.command == {
    "cd login": lambda: self.root.change_directory("login"),
    "cd home": lambda: self.root.change_directory("home")
}

但看起来生成的两个 lambda 函数完全一样:

but it looks like the two lambda function generated are exactly the same :

# Result :
self.command == {
    "cd login": lambda: self.root.change_directory("login"),
    "cd home": lambda: self.root.change_directory("login")   # <- Why login ?
}

我真的不明白为什么.你有什么建议吗?

I really don't understand why. Do you have any suggestions ?

推荐答案

您需要为每个创建的函数绑定 d.一种方法是将其作为具有默认值的参数传递:

You need to bind d for each function created. One way to do that is to pass it as a parameter with a default value:

lambda d=d: self.root.change_directory(d)

现在函数内部的 d 使用参数,即使它具有相同的名称,并且在创建函数时评估它的默认值.为了帮助您了解这一点:

Now the d inside the function uses the parameter, even though it has the same name, and the default value for that is evaluated when the function is created. To help you see this:

lambda bound_d=d: self.root.change_directory(bound_d)

记住默认值是如何工作的,例如对于列表和字典这样的可变对象,因为您正在绑定一个对象.

Remember how default values work, such as for mutable objects like lists and dicts, because you are binding an object.

这种带有默认值的参数习语已经足够常见,但如果您内省函数参数并根据它们的存在确定要做什么,则可能会失败.您可以使用另一个闭包来避免参数:

This idiom of parameters with default values is common enough, but may fail if you introspect function parameters and determine what to do based on their presence. You can avoid the parameter with another closure:

(lambda d=d: lambda: self.root.change_directory(d))()
# or
(lambda d: lambda: self.root.change_directory(d))(d)

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

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