创建一个迭代器的类
class Foo:
def __init__(self,n):
self.n = n
def __iter__(self): #将对象变成一个可迭代对象
return self
def __next__(self): #迭代器需要一个next方法
if self.n == 100:
raise StopIteration('终止')
self.n += 1
return self.n
f1 = Foo(10)
for i in f1: #iter(f1) == f1.__iter__()
print(i)
'''
11
12
13
14
15
16
17
18
19
...
'''
打印斐波拉且数列
class Fib:
def __init__(self):
self._a = 1
self._b =1
print(self._a,self._b,end=' ')
def __iter__(self):
return self
def __next__(self):
if self._b>1000:
raise StopIteration("stopd")
self._a,self._b=self._b,self._a+self._b
return self._a,self._b
a = Fib()
for i in a:
print(i[1],end=' ')
'''
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
'''