将lambda函数存储到字典中时,我遇到了一些奇怪的行为:如果尝试将某个默认值传递给循环中的函数,则只使用最后一个默认值.
这是一些最小的例子:
#!/usr/bin/env python
# coding: utf-8
def myfct(one_value, another_value):
"do something with two int values"
return one_value + another_value
fct_dict = {'add_{}'.format(number): (lambda x: myfct(x, number))
for number in range(10)}
print('add_3(1): {}, id={}'.format(fct_dict['add_3'](1), id(fct_dict['add_3'])))
print('add_5(1): {}, id={}'.format(fct_dict['add_5'](1), id(fct_dict['add_5'])))
print('add_9(1): {}, id={}'.format(fct_dict['add_9'](1), id(fct_dict['add_9'])))
Run Code Online (Sandbox Code Playgroud)
输出如下
add_3(1): 10, id=140421083875280
add_5(1): 10, id=140421083875520
add_9(1): 10, id=140421083876000
Run Code Online (Sandbox Code Playgroud)
你得到不同的函数(id不相同),但每个函数使用相同的第二个参数.
有人能解释一下发生了什么吗?
python2,python3,pypy也是如此......