Chinaunix首页 | 论坛 | 博客
  • 博客访问: 464990
  • 博文数量: 63
  • 博客积分: 1485
  • 博客等级: 上尉
  • 技术积分: 596
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-21 14:49
文章分类

全部博文(63)

文章存档

2018年(8)

2017年(25)

2016年(10)

2012年(6)

2010年(14)

我的朋友

分类: Python/Ruby

2017-01-02 17:47:33

这个文章不错:
Python函数式编程指南(三):迭代器

说起来,之前的编程主要是C,没用过迭代。这跟循环有什么区别?

看《Python基础教程》,看到这里,有点晕:

  1. 一个实现了__iter__方法的对象是可迭代的,一个实现了next方法的对象是迭代器。

写个代码来看看:

点击(此处)折叠或打开

  1. class FF:
  2.    def __init__(self):
  3.       self.a = 0
  4.       print ">>> in __init__: ", self.a
  5.    def next(self):
  6.       print ">>> in __next__: ", self.a
  7.       if self.a > 3:
  8.           raise StopIteration
  9.       self.a = self.a + 1
  10.       return self.a
  11.    def __iter__(self):
  12.       print ">>> in __iter__: ", self.a
  13.       return self

  14. print "===================="
  15. ff=FF()
  16. print "==== After the generation of the instance ===="

  17. def loop(i):
  18.   print "==== start loop ", i, "===="
  19.   for i in ff:                             ## 调用了__iter__,然后再每次的循环中diaoyon
  20.     print "==== start each loop ===="
  21.     print i
  22.     print "==== end ================"

  23. loop(1)
  24. print ""
  25. loop(2)

输出:

点击(此处)折叠或打开

  1. ====================
  2. >>> in __init__: 0
  3. ==== After the generation of the instance ====
  4. ==== start loop 1 ====
  5. >>> in __iter__: 0
  6. >>> in __next__: 0
  7. ==== start each loop ====
  8. 1
  9. ==== end ================
  10. >>> in __next__: 1
  11. ==== start each loop ====
  12. 2
  13. ==== end ================
  14. >>> in __next__: 2
  15. ==== start each loop ====
  16. 3
  17. ==== end ================
  18. >>> in __next__: 3
  19. ==== start each loop ====
  20. 4
  21. ==== end ================
  22. >>> in __next__: 4

  23. ==== start loop 2 ====
  24. >>> in __iter__: 4
  25. >>> in __next__: 4

同样的实例,如果调用loop函数,直接这么操作得到一个列表:

点击(此处)折叠或打开

  1. print "===================="
  2. ff=FF()
  3. print "==== After the generation of the instance ===="
  4. myiter=list(ff)
  5. print myiter

输出结果:

点击(此处)折叠或打开

  1. ====================
  2. >>> in __init__: 0
  3. ==== After the generation of the instance ====
  4. >>> in __iter__: 0
  5. >>> in __next__: 0
  6. >>> in __next__: 1
  7. >>> in __next__: 2
  8. >>> in __next__: 3
  9. >>> in __next__: 4
  10. [1, 2, 3, 4]




阅读(1337) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~