Python 斐波那契数列 Iterator 版本

发布时间 2023-03-22 21:08:51作者: 筱筱的春天
class Fabonacci(object):

    def __init__(self, num):
        #fabonni number
        self.num = num
        self.a = 1
        self.b = 1
        self.current_index = 0

    # __iter__
    def __iter__(self):
        return self

    #__next__
    def __next__(self):
        #1. judge if exceed
        if self.current_index < self.num:
            data = self.a
            self.a, self.b = self.b, self.a + self.b
            self.current_index += 1
            print("index = %d, a = %d, b = %d" % (self.current_index, self.a, self.b))
            return data
        #2. exceed
        else:
            raise StopIteration


if __name__ == '__main__':
    fabo_iteration = Fabonacci(5)
    for value in fabo_iteration:
    # value = next(fabo_iteration)
        print(value)