延时绑定
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.
即闭包中变量的绑定发生在闭包被调用时, 而非闭包定义时.
实例
# 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
需要注意的是, 对于第二个例子closure_test2()
, 在调用完make_closure(i)
(i < 3)之后, 循环里的i值改变了, 然而make_closure()
函数中的i是不会受到影响的, 这一点从输出的id值也可以看出.
网友评论
这一句话对闭包延迟绑定的理解有巨大帮助,谢谢!