__iter__
和__next__()
方法。 __iter__()
方法:返回迭代器对象本身;__next__()
方法:返回容器中的下一个元素,在结尾时引发StopIteration异常终止迭代器。__iter__()
方法。iter()
测试。>>> iter([6,8,10])#返回listterator对象
0x7f992a891210>
>>> iter({'a':1,'b':2})#返回dictionary-keyiterator对象
0x7f992a880838>
>>> iter(666)#不是可迭代对象
Traceback (most recent call last):
File "" , line 1, in
TypeError: 'int' object is not iterable
iter()
转化为iterator。iter()
、next()
,本质上都是用的对象的__iter__()
、__next__()
的方法。enumerate()
找回这个索引值。但对于无法随机访问的数据结构:set()
,迭代器是唯一的访问元素的方式。fab(max)
中用print打印会导致函数的可复用性变差,因此fab返回None。其他函数无法获得fab函数返回的数列;next()
不断返回数列的下一个,内存占用始终为常数。#代码一:
def fab(max):
L = []
n, a, b = 0, 0, 1
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L
#代码二:
def fab(max):
n, a, b = 0, 0, 1
while n < max:
print b
a, b = b, a + b
n = n + 1
#代码三:
class Fab(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def next(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
>>> iter(range(5))
object at 0x7f992a8911d0>
>>> iter(xrange(5))
object at 0x7f992a892240>
next()
方法访问下一个元素:>>> a.next()
0
>>> a.next()
1
>>> a.next()
2
>>> a.next()
3
>>> a.next()
4
>>> a.next()
Traceback (most recent call last):
File "" , line 1, in <module>
StopIteration
处理方法:
lst = range(5)
it = iter(lst)
try:
while True:
val = it.next()
print val
except StopIteration:
pass
#输出
0
1
2
3
4
注意:Python专门为for关键字做了迭代器的语法糖:在for循环中,Python将自动调用内置函数iter()获得迭代器,自动调用next()获取元素,还完成了检查StopIteration异常的工作。
下面例子中实现了一个MyRange的类型,这个类型中实现了__iter__()
方法,通过这个方法返回对象本身作为迭代器对象;同时,实现了next()
方法用来获取容器中的下一个元素,当没有可访问元素后,就抛出StopIteration异常。
class MyRange(object):
def __init__(self, n):
self.idx = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.idx < self.n:
val = self.idx
self.idx += 1
return val
else:
raise StopIteration()
myRange = MyRange(5)
for i in myRange:
print i
#输出:
0
1
2
3
4