循環不Python中介紹的範圍,因此,所有三個功能關閉在同一i
變量,將引用循環結束後其最終價值,這是2
它好像幾乎每個人我與誰在Python中使用閉包交談已經被這個咬傷了。推論是外部函數可以改變i
,但內部函數不能(因爲這會使得i
成爲本地的,而不是基於Python的語法規則的閉包)。
有解決這個方法有兩種:
# avoid closures and use default args which copy on function definition
for i in xrange(3):
def func(x, i=i):
return x*i
flist.append(func)
# or introduce an extra scope to close the value you want to keep around:
for i in xrange(3):
def makefunc(i):
def func(x):
return x*i
return func
flist.append(makefunc(i))
# the second can be simplified to use a single makefunc():
def makefunc(i):
def func(x):
return x*i
return func
for i in xrange(3):
flist.append(makefunc(i))
# if your inner function is simple enough, lambda works as well for either option:
for i in xrange(3):
flist.append(lambda x, i=i: x*i)
def makefunc(i):
return lambda x: x*i
for i in xrange(3):
flist.append(makefunc(i))
[Python中的詞彙關閉]的可能重複(http://stackoverflow.com/questions/233673/lexical-closures-in-python) – BrenBarn 2012-07-10 07:32:33