1.iter()
魔法方法:__iter__()
2.next()
魔法方法:__next__()
>>> string = 'FishC'
>>> it = iter(string)
>>> next(it)
'F'
>>> next(it)
'i'
>>> next(it)
's'
>>> next(it)
'h'
>>> next(it)
'C'
>>> next(it)
>>> while True:
try:
each = next(it)
except StopIteration:
break
print(each)
F
i
s
h
C
h实现斐波那契数列,并且可以指定停止的最大值
>>> 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
return self.a
>>> fibs1 = fibs()
>>> for each in fibs1:
print(each)
1
1
2
3
5
8
>>> fibs1 = fibs(100)
>>> for each in fibs1:
print(each)
1
1
2
3
5
8
13
21
34
55
89