可以这么说,Python中的闭包表现为“奇数”。
考虑以下代码片段,其中我尝试以两种方式基于foo
构建闭包列表:在bad_closure
中,闭包是“即时”构建的,而在good_closure
中闭包由辅助函数构建:
def foo(d):
return d + 1
def bad_closure():
''' shares resources implicitly '''
# list of 5 closures
# `i` is shared between all closures
cls = [lambda : foo(i) for i in range(5)]
return cls
def good_closure():
''' no resource sharing '''
def mk_cl(i):
''' helper to make a closure'''
c_ = lambda : foo(i)
return c_
# list of 5 closures
# each closure has its own `i`
cls = [mk_cl(i) for i in range(5)]
return cls
#--- TEST ---
bs = bad_closure()
print([f() for f in bs]) # output: [5, 5, 5, 5, 5]
gs = good_closure()
print([f() for f in gs]) # output: [1, 2, 3, 4, 5]
结果惊人地不同。似乎在bad_closure
中,闭包各取一个固定 i
,但它们全部 share 和 s { {1}}每次迭代都会更新(最后取值i
)!相反,在5
中,good_closure
是分开的-正如我期望的那样。
我想看看幕后发生的事情以及原因。