루프 내부에서 함수를 만들고 사전에 저장하려고합니다. 문제는 사전의 모든 항목이 마지막으로 생성 된 기능에 매핑되는 것으로 보입니다. 코드는 다음과 같이 진행됩니다루프에서 함수 만들기
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/ko/latest/writing/gotchas/#late-binding-closures –