python lambda的应用_循环中的Python Lambda

本文探讨了Python中字典迭代与闭包结合时出现的问题。当尝试创建一个字典,其中键对应的值是使用lambda表达式和默认参数的函数时,发现所有函数引用的都是同一个默认参数。解释了这是因为默认参数在函数定义时被初始化,而非每次调用。解决方案是通过使用闭包或者将参数绑定到函数中来确保每个函数拥有独立的参数副本。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

Considering the following code snippet :

# directorys == {'login': , 'home': }

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")

}

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 ?

解决方案

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)

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值