Python新手如何进行闭包时绑定变量操作
作者:爱喝马黛茶的安东尼 发布时间:2021-05-01 15:23:55
标签:Python,闭包,绑定变量
搞不清楚在闭包(closures)中Python是怎样绑定变量的
看这个例子:
>>> 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
实例扩展:
# 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
来源:https://www.py.cn/jishu/jichu/10531.html


猜你喜欢
- 我为一大型网站做了一个论坛,也顺利通过了测试。由于是第一次做这方面的数据库,我不知道比其它网站上数据库差距有多大,是不是够优化。能推荐或介绍
- 本文实例讲述了C#简单访问SQLite数据库的方法。分享给大家供大家参考,具体如下:下载最新版SQLite(http://www.sqlit
- 很多网站都有“浏览历史”这个功能,通常都是显示在页面的一侧,特别是一些购物网站,这个功能会让用户使用网站的体验好一些;例如当当网或淘宝网都有
- 一、什么是索引 减少磁盘I/O和逻辑读次数的最佳方法之一就是使用【索引】 索引允许SQL Server在表中查找数据而不需要扫描整个表。 1
- window.onload=function() {&
- 按下"开始(win)"按钮和R键,输入cmd,打开命令行寻找点击需要的库:https://www.lfd.uci.edu
- 前言Helium工具是对Selenium的封装,将Selenium工具的使用变得更加简单。Selenium虽然好,但是在它的使用过程中元素的
- 一、下载1.mysql官网下载地址:https://downloads.mysql.com/archives/community/2.下载完
- 哪里出问题了python 中,使用 global 会将全局变量设为本函数可用。同时,在函数内部访问变量会先本地再全局。在嵌套函数中,使用 g
- 类和实例python是一个面向对象的语言,而面向对象最重要的概念就是类和实例, 记得刚学习的时候不太理解这些概念,直到老师说了一句”物以类聚
- pycharm中光标变粗,如下:原因:光标进入了改写状态。解决方法:按一下键盘中的Insert键就好了。
- 一、背景 PyCharm执行Python时,找不到自己安装的package,例如pandas、numpy、scipy、scikit等,在执行
- 日期时间转字符串Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AM
- 其实有一个疑惑一直在小编心中,每一个代码段编写里,总会出现好多个函数,也许有人和小编有一样的认同感,后来,小编明白,每一个函数本身都是都有各
- python断言assert语句assert语句的格式是【assert 表达式,返回数据】,当表达式为False时则触发AssertionE
- 最近几年,jupyter在全球数据科学领域,已经成为不可或缺的重要工具。在jupyter中用python写程序,若import了自己写的外部
- 最近遇到了Python访问SqlServer的问题,这里总结下。一、Windows下配置Python访问Sqlserver环境:Window
- 一、简介pandas中的ExcelFile()和ExcelWriter(),是pandas中对excel表格文件进行读写相关操作非常方便快捷
- 本文实例讲述了Python数组定义方法。分享给大家供大家参考,具体如下:Python中没有数组的数据结构,但列表很像数组,如:a=[0,1,
- 首先,如果以前安装的话,要删除干净。我也找了