1. 程式人生 > >自定義迭代器實現斐波那契數列

自定義迭代器實現斐波那契數列

#斐波那契阿數列

class fib:
    def __init__(self):
        self.pre=0
        self.cou=1

    def __iter__(self):
        return self
    def __next__(self):
     #0 1 2 3 5 8 13
        # print(self.pre)  #0
        # print(self.cou)  #1
        self.cou,self.pre = self.pre+self.cou,self.cou
        print(self.cou)

if __name__=='__main__':

    f = fib()
    i = 0
    while i < 10:
        if i==0:
            print(i)
        # print(i)
        f.__next__()

        i += 1