搞不清楚在闭包(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
标签:
Python,闭包,绑定变量
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金钱帮资源网 Copyright www.kbjia.com
暂无“Python新手如何进行闭包时绑定变量操作”评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神】V5.0攻略 | 林尼攻略一图流
- 李翊君.1993-相思的烈酒【上华】【WAV+CUE】
- 古巨基.1998-LEO.KU(国)【千禧年代】【WAV+CUE】
- 郭子.2001-原来你什么都不想要创作集丫滚石】【WAV+CUE】
- 《使命召唤:黑色行动6》新预告公布!10月25日发售
- Atlus《暗喻幻想》媒体评分汇总:高分好评如潮!
- 2024金摇杆奖提名揭晓 《黑神话》角逐最佳视觉设计!
- 群星《新说唱2024 第3期 (上)》[320K/MP3][32.76MB]
- 群星《新说唱2024 第3期 (上)》[FLAC/分轨][95.38MB]
- 群星《新说唱2024 第3期 (下)》[320K/MP3][31.36MB]
- 幻兽帕鲁手游什么时候正式上线 最新消息一览
- 西普大陆BOSS位置盘点 解锁天启纪元玩法
- 西普大陆精灵进阶培养攻略 精灵养成指南
- dnf手游法控法系职业哪个强 dnf手游法控法系职业强度排行
- 魔兽世界血藤护目镜图纸在哪买 wlk血藤护目镜图纸购买位置介绍