可以直接作用于for循环的对象统称为可迭代对象:Iterable
可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
用迭代器实现斐波那契数列
Python3环境下可实现迭代:
class Fib(object):
def __init__(self, max):
super(Fib, self).__init__()
self.max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def __next__(self):
fib = self.a
if fib > self.max:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib
# 定义一个main函数,循环遍历每一个菲波那切数
def main():
# 20以内的数
fib = Fib(20)
for i in fib:
print(i)
# 测试
if __name__ == '__main__':
main()
0
1
1
2
3
5
8
13
Python2环境下运行报错:
TypeError: iter() returned non-iterator of type ‘Fib’
def _next_(self) is for Python 3
For Python 2 you need to add method next()
class Fib(object):
def __init__(self, max):
super(Fib, self).__init__()
self.max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def __next__(self):
fib = self.a
if fib > self.max:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib
def next(self):
return self.__next__()
def main():
fib = Fib(20)
for i in fib:
print(i)
if __name__ == '__main__':
main()