2019年9月5日 迭代器协议
迭代器协议:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么异常
可迭代对象:实现了迭代器协议的对象,对象内部定义一个__iter__ 方法
class Foo: def __init__(self,n): self.n=n def __iter__(self): return self def __next__(self): if self.n==9: raise StopIteration('over') self.n += 1 return self.n f1=Foo(3) # print(f1.__next__()) # print(next(f1)) for i in f1:#f1.__iter__ >>iter(f1) print(i)#f1.__next__ 调用next方法,并捕捉异常终止for循环 # 迭代器协议:必须要有 iter 和 next
》》》
4
5
6
7
8
9