一、闭包
1、闭包的概念
- 闭包函数必须返回一个函数对象
- 闭包函数返回的函数必须应用外部变量
2、示例
1 def f1(a, b): 2 def f2(x): 3 return a*x+b 4 return f2 5 6 7 test1 = f1(2, 1) 8 test2 = f1(3, 2)
9 print(test1(10)) # 21 10 print(test2(10)) # 32
11 print(test1) # <function f1.<locals>.f2 at 0x000002D89A3C68C8> 12 print(test2) # <function f1.<locals>.f2 at 0x000002D8AAAF09D8>
#__closure__属性返回一个元组,包含闭包引用的外部变量 13 print(test1.__closure__) # (<cell at 0x000002D8ABD9A768: int object at 0x00007FFC2D18B370>, <cell at 0x000002D8ABD9A708: int object at 0x00007FFC2D18B350>) 14 print(test2.__closure__) # (<cell at 0x000002D8ABD9A7F8: int object at 0x00007FFC2D18B390>, <cell at 0x000002D8ABD9A7C8: int object at 0x00007FFC2D18B370>) 15 for i in test1.__closure__: 16 print(i.cell_contents) # 2 # 1