Python 闭包变量绑定问题

延时绑定

原文

Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called.

即闭包中变量的绑定发生在闭包被调用时, 而非闭包定义时.

实例

# coding=utf-8
__author__ = 'xiaofu'

# 解释参考 http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures

def closure_test1():
    """
    每个closure的输出都是同一个i值
    :return:
    """
    closures = []
    for i in range(4):
        
        def closure():
            print("id of i: {}, value: {} ".format(id(i), i))

        closures.append(closure)

    # Python’s closures are late binding.
    # This means that the values of variables used in closures are looked up at the time the inner function is called.

    for c in closures:
        c()

def closure_test2():

    def make_closure(i):

        def closure():
            print("id of i: {}, value: {} ".format(id(i), i))

        return closure

    closures = []

    for i in range(4):
        closures.append(make_closure(i))

    for c in closures:
        c()


if __name__ == '__main__':
    closure_test1()
    closure_test2()

输出:

id of i: 10437280, value: 3 
id of i: 10437280, value: 3 
id of i: 10437280, value: 3 
id of i: 10437280, value: 3 
id of i: 10437184, value: 0 
id of i: 10437216, value: 1 
id of i: 10437248, value: 2 
id of i: 10437280, value: 3

需要注意的是, 对于第二个例子closure_test2(), 在调用完make_closure(i)(i < 3)之后, 循环里的i值改变了, 然而make_closure()函数中的i是不会受到影响的, 这一点从输出的id值也可以看出.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 以下翻译自Apple官方文档,结合自己的理解记录下来。翻译基于 swift 3.0.1 原文地址 Closure...
    艺术农阅读 5,542评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,103评论 19 139
  • I recommend executing this file, then reading it alongsid...
    YongpingZhao阅读 5,675评论 0 0
  • 【感恩日记】 今早跟小水姐姐一起走圈儿,许是受了我的影响吧,姐姐边走边拍照,把校园里的美景纷纷摄入镜头。于是顺着她...
    碧水无痕阅读 1,774评论 0 0
  • 昨天晚上回来和朋友约好在家里打麻将,这是我非常喜欢的。为了防止困,提前喝了一杯咖啡,早上起来的太早,又带儿子上...
    byseam阅读 1,760评论 0 0

友情链接更多精彩内容