迭代器和生成器
和迭代器相關(guān)的魔術(shù)方法(__iter__和__next__)
兩種創(chuàng)建生成器的方式(生成器表達式和yield關(guān)鍵字)
def fib(num):
? ? """生成器"""
? ? a, b = 0, 1
? ? for _ in range(num):
? ? ? ? a, b = b, a + b
? ? ? ? yield a
?
?
class Fib(object):
? ? """迭代器"""
? ?
? ? def __init__(self, num):
? ? ? ? self.num = num
? ? ? ? self.a, self.b = 0, 1
? ? ? ? self.idx = 0
?
? ? def __iter__(self):
? ? ? ? return self
? ? def __next__(self):
? ? ? ? if self.idx < self.num:
? ? ? ? ? ? self.a, self.b = self.b, self.a + self.b
? ? ? ? ? ? self.idx += 1
? ? ? ? ? ? return self.a
? ? ? ? raise StopIteration()