zoukankan      html  css  js  c++  java
  • 迭代器协议,迭代器协议实现斐波那契数列

    '''迭代器协议'''
    # 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...')
  • 相关阅读:
    C#中方法的分类、定义、调用(3)
    C#中的输入和输出与类和对象(2)
    .net中的数据类型与数据转换(1)
    android第二章控件2
    android第二章控件1
    安卓 第一章
    二进制文件的读写与小结
    字符流
    File类与字节流
    字节流
  • 原文地址:https://www.cnblogs.com/xuewei95/p/14722978.html
Copyright © 2011-2022 走看看