斐波那契数列数列class类 python实现

实例可从一开始迭代,可调用,同时实现缓存,不用重复计算

import time


class Fibos:
    def __init__(self):
        self.items = [0]
        self.gen = self.fibos()

    def fibos(self, first=0, second=1):
        while True:
            first, second = second, first + second
            self.items.append(first)
            yield first

    def __iter__(self):
        lenth = len(self.items)
        for i in range(1, lenth):
            yield self.items[i]
        else:
            yield from self.gen

    def __getitem__(self, n):
        lenth = len(self.items)
        if n <= lenth - 1:
            return self.items[n]
        for i in range(lenth, n):
            next(self.gen)
        return next(self.gen)

    def __call__(self, n):
        return self[n]


# 用法
f = Fibos()
print(f(10))
print(f[10])
for fib in f:
    print(fib)
    time.sleep(1)
    break

猜你喜欢

转载自blog.csdn.net/qq_33287645/article/details/80293551