代码
class Fibonacci(object):
def __init__(self, number):
self.x = 0
self.y = 1
self.current_number = 0
self.all_number = number
def __iter__(self):
"""可迭代对象, 返回本身作为一个迭代器"""
return self
def __next__(self):
"""迭代器会自动调用__next__方法"""
if self.current_number < self.all_number:
fibonacci_number = self.x
self.x, self.y = self.y, self.x + self.y
self.current_number += 1
return fibonacci_number
else:
raise StopIteration
if __name__ == '__main__':
fibonacci = Fibonacci(10)
for num in fibonacci:
print(num, end=", ")
print()
print(list(Fibonacci(10)))
print(tuple(Fibonacci(10)))
运行结果
判断是否为迭代器对象
import collections
print(isinstance(fibonacci, collections.Iterator))