#任何实现了 __iter__
和 __next__
方法的对象都是迭代器,所以生成器是一种特殊的迭代器
#生成器的标志是yied 函数
class Range:
def __init__(self, start, end=None, step=1):
if end is None:
self.end = start
self.start = 0
else:
self.start = start
self.end = end
self.step = step
def __iter__(self):
return self
def __next__(self):
if self.start < self.end:
current = self.start
self.start += self.step
return current
else:
raise StopIteration()
#定义一个迭代器, 实现斐波那契数列
class Fib:
def __init__(self, max_value):
self.prev = 0
self.curr = 1
self.max_value = max_value
def __iter__(self):
return self
def __next__(self):
if self.curr <= self.max_value:
res = self.curr
self.prev, self.curr = self.curr, self.prev + self.curr # 为下一次做准备
return res
else:
raise StopIteration()
# 定义一个生成器函数, 实现斐波那契数列
def fib(max_value):
prev = 0
curr = 1
while curr < max_value:
yield curr
prev, curr = curr, curr + prev