这个文章不错:
Python函数式编程指南(三):迭代器
说起来,之前的编程主要是C,没用过迭代。这跟循环有什么区别?
看《Python基础教程》,看到这里,有点晕:
-
一个实现了__iter__方法的对象是可迭代的,一个实现了next方法的对象是迭代器。
写个代码来看看:
-
class FF:
-
def __init__(self):
-
self.a = 0
-
print ">>> in __init__: ", self.a
-
def next(self):
-
print ">>> in __next__: ", self.a
-
if self.a > 3:
-
raise StopIteration
-
self.a = self.a + 1
-
return self.a
-
def __iter__(self):
-
print ">>> in __iter__: ", self.a
-
return self
-
-
print "===================="
-
ff=FF()
-
print "==== After the generation of the instance ===="
-
-
def loop(i):
-
print "==== start loop ", i, "===="
-
for i in ff: ## 调用了__iter__,然后再每次的循环中diaoyon
-
print "==== start each loop ===="
-
print i
-
print "==== end ================"
-
-
loop(1)
-
print ""
-
loop(2)
输出:
-
====================
-
>>> in __init__: 0
-
==== After the generation of the instance ====
-
==== start loop 1 ====
-
>>> in __iter__: 0
-
>>> in __next__: 0
-
==== start each loop ====
-
1
-
==== end ================
-
>>> in __next__: 1
-
==== start each loop ====
-
2
-
==== end ================
-
>>> in __next__: 2
-
==== start each loop ====
-
3
-
==== end ================
-
>>> in __next__: 3
-
==== start each loop ====
-
4
-
==== end ================
-
>>> in __next__: 4
-
-
-
==== start loop 2 ====
-
>>> in __iter__: 4
-
>>> in __next__: 4
同样的实例,如果调用loop函数,直接这么操作得到一个列表:
-
print "===================="
-
ff=FF()
-
print "==== After the generation of the instance ===="
-
myiter=list(ff)
-
print myiter
输出结果:
-
====================
-
>>> in __init__: 0
-
==== After the generation of the instance ====
-
>>> in __iter__: 0
-
>>> in __next__: 0
-
>>> in __next__: 1
-
>>> in __next__: 2
-
>>> in __next__: 3
-
>>> in __next__: 4
-
[1, 2, 3, 4]
阅读(1400) | 评论(0) | 转发(0) |