Python闭包中的共享和本地化变量

2024-04-19 14:04:22 发布

您现在位置:Python中文网/ 问答频道 /正文

可以说,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是分开的——正如我所预料的那样

我想看看幕后发生了什么,为什么


Tags: oflambdainforreturnfoodef方式