斐波那契数列

斐波那契数列是由 0, 1, 1, 2, 3, 5, 8...构成
请编写一个Fib类,Fib(10)表示数列的前10个元素,print Fib(10) 可以打印出数列的前 10 个元素

list = ['0', '1']


class Fib:

   def __init__(self, n):
       self.n = n
       self.fib = None

   def sum(self):
       n1 = 0
       n2 = 1
       a = 3
       if self.n == 1:
           self.fib = list[0]
       elif self.n == 2:
           self.fib = list
       else:
           while a <= self.n:
               nn = n1 + n2
               list.append('%s' % nn)
               self.fib = list
               n1 = n2
               n2 = nn
               a += 1
           return self.fib

   def __len__(self):
       return len(self.fib)

   def __getitem__(self, item):
       return self.fib[item]

if __name__=="__main__":
   a = Fib(10)
   print(a.sum())
   print(len(a))
   print(a[5])

你可能感兴趣的:(斐波那契数列)