前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python新手如何进行闭包时绑定变量操作

Python新手如何进行闭包时绑定变量操作

作者头像
砸漏
发布2020-11-02 11:02:00
4150
发布2020-11-02 11:02:00
举报
文章被收录于专栏:恩蓝脚本

搞不清楚在闭包(closures)中Python是怎样绑定变量的

看这个例子:

代码语言:javascript
复制
    def create_multipliers():
...   return [lambda x : i * x for i in range(5)]
    for multiplier in create_multipliers():
...   print multiplier(2)
...

期望得到下面的输出:

0 2 4 6 8

但是实际上得到的是:

8 8 8 8 8

实例扩展:

代码语言:javascript
复制
# 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()

输出:

代码语言:javascript
复制
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

到此这篇关于Python新手如何进行闭包时绑定变量操作的文章就介绍到这了,更多相关Python闭包时绑定变量实例内容请搜索ZaLou.Cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档