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

时间:2018-07-05 14:12:33

标签: python closures shared-resource

可以这么说,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是分开的-正如我期望的那样。

我想看看幕后发生的事情以及原因。

0 个答案:

没有答案