1. iter函数
iter 函数只是调用对象的__iter__
方法,这个方法按照协议会返回一个迭代器,使得for循环这样的语法结构能够进行下去。
2. 可迭代对象
一个对象实现了__iter__方法,就是可迭代的,可以使用for循环访问对象中的每个元素,其实质是调用iter函数使对象返回一个迭代器,再使用迭代器进行循环。
3. 迭代器:实现了__next__()方法,调用该方法时,直到对象没有可调用的元素就返回异常StopIteration
>>> st = 'Hello'
>>> for i in st:
... print(i)
...
H
e
l
l
o
>>> next(st)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object is not an iterator
>>> st = iter(st)
>>> next(st)
'H'
>>> next(st)
'e'
>>> next(st)
'l'
>>> next(st)
'l'
>>> next(st)
'o'
>>> next(st)
Traceback (most recent call last):
File "", line 1, in
StopIteration
>>> class Fibs:
... def __init__(self,n=10):
... self.a = 0
... self.b = 1
... self.n = n
... def __iter__(self):
... return self
... def __next__(self):
... self.a,self.b = self.b,self.a+self.b
... if self.a > self.n:
... raise StopIteration
... else:
... return self.a
...
>>> f = Fibs(20)
>>> for i in f:
... print(i)
...
1
1
2
3
5
8
13