实现一个可迭代的类,需要在类里面定义两种方法:
1. __iter__():返回iterator对象本身
2. next():每当next()方法被调用时,返回下一个值,直到抛出StopIteration的异常
1 class Fabonacci(object): 2 """Fabonacci Class 3 4 Return Fabonacci Number 5 """ 6 def __init__(self, num): 7 self.num = num 8 self.n, self.a, self.b = 0, 0, 1 9 10 def __iter__(self): 11 return self 12 13 def next(self): 14 if self.n < self.num: 15 result = self.b 16 self.a, self.b = self.b, self.a+self.b 17 self.n = self.n + 1 18 19 return result 20 21 raise StopIteration() 22 23 if __name__ == "__main__": 24 25 fab = Fabonacci(5) 26 27 for n in fab: 28 print n 29