小编这次要给大家分享的是详解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
看完这篇关于详解Python如何进行闭包时绑定变量操作的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。