可以说,Python中的闭包的行为方式是“奇怪的”。 考虑下面的代码片段,在这里我尝试用两种方式构建基于{{CD1>}的闭包列表:在{{CD2>}中,闭包是在“飞”中建立的,而在{{CD3>}中,闭包是由辅助函数构建的:
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
,但是它们都共享相同的i
,该值通过每次迭代进行更新(最后取值5
)!相反,在good_closure
中,i
是分开的——正如我所预料的那样
我想看看幕后发生了什么,为什么
目前没有回答
相关问题 更多 >
编程相关推荐