迭代器协议,迭代器协议实现斐波那契数列

'''迭代器协议'''
# l = list('hello')
# for i in l:
#  print(i)

# class Foo:
#  def __iter__(self):
#     pass
#
# f1 = Foo()
#
# for i in f1: # iter(f1) ---> f1.__iter__()
#  print(i)
# 没加__iter__方法没加__next__方法,报错信息为:TypeError: 'Foo' object is not iterable
# 加了__iter__方法没加__next__方法,但__iter__方法没有任何操作(函数体为pass),报错信息为:TypeError: iter() returned non-iterator of type 'NoneType'


class Foo:
   def __init__(self, num):
      self.num = num

   def __iter__(self):
      return self

   def __next__(self):
      if self.num == 1000:
         raise StopIteration('终止循环!')
      self.num += 1
      return self.num

f2 = Foo(10)
print(f2.__next__()) # 11
print(next(f2)) # 12

for i in f2:
   print(i)


'''迭代器协议实现斐波那契数列'''
class Fib:
   def __init__(self):
      self.a = 1
      self.b = 1

   def __iter__(self):
      return self

   def __next__(self):
      if self.a > 1000:
         raise StopIteration('终止')
      self.a, self.b = self.b, self.a+self.b
      return self.a

f3 = Fib()
for i in f3:
   print(i)
while True: print('studying...')
原文地址:https://www.cnblogs.com/xuewei95/p/14722978.html