zoukankan      html  css  js  c++  java
  • 迭代器协议

     1 class Foo:
     2     '迭代器协议:对象可以调用next()方法,且当不可迭代的时候会产生stopiteration,且只能向后,不能向前。'
     3     a = 10
     4 
     5     def __iter__(self):  # 根据迭代器协议定义一个__iter__()方法
     6         return self
     7 
     8     def __next__(self):  # 根据迭代器协议定义一个next()方法
     9         if self.a <=13:
    10             self.a += 1
    11             return self.a
    12         raise StopIteration('终止程序')
    13 
    14 f1 = Foo()
    15 print(f1.__next__())  # 调用next()方法
    16 print(f1.__next__())
    17 # print(next(f1))
    18 # print(next(f1))
    19 # print(next(f1))
    20 # print(next(f1))
    21 for i in f1:  # 实际是先调用了f1.__iter__()------->iter(f1) 变为可迭代对象 然后调用next()方法
    22     print(i)
    23 输出:
    24 11
    25 12
    26 13
    27 14
  • 相关阅读:
    作业二
    作业一
    作业十一
    作业十
    作业九
    作业八
    作业七
    作业六
    作业五
    JAVA第三次作业
  • 原文地址:https://www.cnblogs.com/ch2020/p/12449122.html
Copyright © 2011-2022 走看看