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-closuresdef 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
到此这篇关于Python新手如何进行闭包时绑定变量操作的文章就介绍到这了,更多相关Python闭包时绑定变量实例内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
1. Python变量格式化输出实现原理解析2. 基于SpringBoot集成测试远程连接Redis服务的教程详解3. HTML DOM setInterval和clearInterval方法案例详解4. PHP输入流php://input的使用分析5. SpringBoot集成validation校验参数遇到的坑6. 浅谈JavaScript中等号、双等号、 三等号的区别7. IIS Express 取代 ASP.NET Development Server的配置方法8. PHP的面向对象编程:开发大型PHP项目的方法(一)9. asp+JMAIL实现发送邮件10. php strncmp函数原型源码分析

网公网安备