39
我試圖在循環中創建函數並將它們存儲在字典中。 問題是,字典中的所有條目似乎都會映射到最後創建的函數。該代碼是這樣的:在循環中創建函數
d = {}
def test(**kwargs):
for k in kwargs:
def f():
print k, kwargs[k]
d[k] = f
f()
test(foo=1, bar=2)
print 'should print the same output as before'
d['foo']()
d['bar']()
此輸出:
foo 1
bar 2
should print the same output as before
bar 2
bar 2
任何想法,爲什麼?
作爲提醒我自己:http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures – 2014-09-10 17:20:52