+ -
当前位置:首页 → 问答吧 → python闭包实现的所谓bug

python闭包实现的所谓bug

时间:2010-12-15

来源:互联网

转:stonelee
思路来自http://groups.google.com/group/p ... 6303de2ec?hl=zh-CN#
整理记录下来,让墙内的人也看看。
问题描述
Python代码
  1. fs = []   
  2. for i in range(10):   
  3.     def f(n):   
  4.         return i + n   
  5.     fs.append(f)   
  6. print [f(4) for f in fs]   
  7. print [id(f(4)) for f in fs]  
复制代码
结果为:
[13, 13, 13, 13, 13, 13, 13, 13, 13, 13]
[145743064, 145743064, 145743064, 145743064, 145743064, 145743064, 145743064, 14
5743064, 145743064, 145743064]
很奇怪的结果吧。
问题所在:
Python代码
  1. fs = []   
  2. for i in range(10):   
  3.     def f(n):   
  4.         print locals()   
  5.         print 'i' in globals()   
  6.         return i + n   
  7.     fs.append(f)   
  8. print [f(4) for f in fs]   
  9. print [id(f(4)) for f in fs]  
复制代码
结果为
locals: {'n': 4}
i in globals is: True   
可以看到i根本就没有封闭在f()里,而是个全局变量,因此出现上面的结果也就不奇怪了。
解决方案:
Python代码
  1. fs = []
  2. for i in range(10):
  3.     def f(n,i = i):
  4.         return i + n
  5.     fs.append(f)
  6. print [f(4) for f in fs]
  7. print [id(f(4)) for f in fs]
复制代码
将全局变量i引入f中,这下结果正确了。
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[143334724, 143334712, 143334700, 143334688, 143334676, 143334664, 143334652, 14
3334640, 143334628, 143334616]

作者: 中关村村草   发布时间: 2010-12-15

这次没有猜到是你,唉,失败~~
先留言,再看~

作者: icyomik   发布时间: 2010-12-15

表示谢谢,完全明解~

作者: icyomik   发布时间: 2010-12-15