发出调用lambda存储在字典中的问题

时间:2013-12-18 13:28:43

标签: python python-2.7 dictionary lambda

我正在学习Python并使用字典和lambda函数的概念。我有以下代码的问题:

def helloName(name):
    print 'hello %s' % name

myList = ['one', 'two', 'three']
myDict = {}

print '====' * 4

for i in myList:
    myDict[i] = lambda: helloName(i)
    print i + ' : ' +  str(myDict[i])

print '====' * 4

myDict['one']()
print myDict['one']
myDict['two']()
print myDict['two']
myDict['three']()
print myDict['three']

print '====' * 4

for i in myList:
    myDict[i]()
    print i + ' : ' +  str(myDict[i])

此脚本的输出为:

================
one : <function <lambda> at 0x0060C330>
two : <function <lambda> at 0x01FB4FB0>
three : <function <lambda> at 0x01FA9570>
================
hello three
<function <lambda> at 0x0060C330>
hello three
<function <lambda> at 0x01FB4FB0>
hello three
<function <lambda> at 0x01FA9570>
================
hello one
one : <function <lambda> at 0x0060C330>
hello two
two : <function <lambda> at 0x01FB4FB0>
hello three
three : <function <lambda> at 0x01FA9570>

我不理解第二块输出线。我期望输出与输出行的第三个块完全相同。

你能帮我理解两个输出之间的区别,并建议修改两次相同的输出吗?

1 个答案:

答案 0 :(得分:2)

这是因为Python的closure属性。解决这个问题

myDict[i] = lambda i=i: helloName(i)

此问题已经回答hereherehereherehere