__iter__和__next__
__iter__(self)和__next__(self)
Python中for循环的原理就是调用可迭代对象的__iter__方法得到迭代器对象,然后调用__next__方法进行取值,直到对象抛出StopIteration异常。某些语言例如go,即支持迭代循环,也支持索引循环。
自定义一个可迭代对象模拟range:
class Range:
def __init__(self,start,stop,step=1):
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
if self.start < self.stop:
n = self.start
self.start += self.step
return n
raise StopIteration()
for i in Range(0,100,):
print(i)
产生小于num的斐波那契数列:
class Fib:
def __init__(self, n):
self.n = n
self.start = 0
self.second = 1
def __iter__(self):
return self
def __next__(self):
if self.start < self.n:
x = self.start
self.start, self.second = self.second, self.start + self.second
return x
raise StopIteration()
for i in Fib(100):
print(i, end=' ')
0 1 1 2 3 5 8 13 21 34 55 89