不能简单讲,这就要看一些底层的东西(堆栈结构等等,估计还和编译原理有关),我觉得重点在于延迟绑定怎么知道绑定的外层函数的局部变量
python的闭包是延迟绑定
#!/usr/bin/python # -*- coding:utf-8 -*- def multipliers(): name = "江湖狗哥我也" i = 0 ret = list() for _ in range(4): lambda_func = lambda x: i * x + (print(name) is None) - 1 # noqa ret.append(lambda_func) print(lambda_func.__closure__) print("the closure variable i: {}".format(hex(id(lambda_func.__closure__[0].cell_contents)))) i += 1 i = 100 return ret if __name__ == '__main__': for item in multipliers(): print("the lambda function output: {}".format(item(2))) print("闭包中的cell对象组成的元组成: {}".format(item.__closure__)) print("取出闭包空间中的整数: {}".format(item.__closure__[0].cell_contents)) for number in list([0, 1, 2, 3, 100]): print(hex(id(number)))
__
(<cell at 0x0000029926818FD0: int object at 0x0000029926026910>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) the closure variable i: 0x29926026910 (<cell at 0x0000029926818FD0: int object at 0x0000029926026930>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) the closure variable i: 0x29926026930 (<cell at 0x0000029926818FD0: int object at 0x0000029926026950>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) the closure variable i: 0x29926026950 (<cell at 0x0000029926818FD0: int object at 0x0000029926026970>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) the closure variable i: 0x29926026970 江湖狗哥我也 the lambda function output: 200 闭包中的cell对象组成的元组成: (<cell at 0x0000029926818FD0: int object at 0x00000299260555D0>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) 闭包中的整数值: 100 江湖狗哥我也 the lambda function output: 200 闭包中的cell对象组成的元组成: (<cell at 0x0000029926818FD0: int object at 0x00000299260555D0>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) 闭包中的整数值: 100 江湖狗哥我也 the lambda function output: 200 闭包中的cell对象组成的元组成: (<cell at 0x0000029926818FD0: int object at 0x00000299260555D0>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) 闭包中的整数值: 100 江湖狗哥我也 the lambda function output: 200 闭包中的cell对象组成的元组成: (<cell at 0x0000029926818FD0: int object at 0x00000299260555D0>, <cell at 0x0000029926818FA0: str object at 0x0000029926576DC0>) 闭包中的整数值: 100 0x29926026910 0x29926026930 0x29926026950 0x29926026970 0x299260555d0
我特意加了一个字符串局部变量, name, 这里其实声明普通函数也可以,特意用了一些比较恶心的用法.
从下面代码我们知道什么
—————
延迟绑定只是一个表面现象,真正要理解我觉得还有一段路要走
看完龙书再回答一波.