Python之迭代器
Posted 非法关键字
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之迭代器相关的知识,希望对你有一定的参考价值。
1.如果有重载__iter__方法则表示类是一个Iterable
2.如果有重载__next__方法则表示类是一个Iterator
3.可以使用isinstance(obj, Iterable)和isinstance(obj, Iterator)来判断一个实例是否是Iterable和Iterator
1 from collections import Iterable 2 from collections import Iterator 3 import time 4 5 6 class MyIterable: 7 """ 8 类的注释 9 """ 10 def __init__(self): 11 self.names = list() 12 self.__ind = 0 13 14 def add(self, name): 15 self.names.append(name) 16 17 def __iter__(self): 18 # return MyIterator(self) 19 return self 20 21 def __next__(self): 22 print(‘return from MyIterable::__next__‘) 23 if len(self.names) > self.__ind: 24 ret = self.names[self.__ind] 25 self.__ind += 1 26 return ret 27 else: 28 raise StopIteration 29 30 31 # class MyIterator(): 32 # """ 33 # 类的注释 34 # """ 35 # def __init__(self, iterable): 36 # self.iterable = iterable 37 # self.__ind = 0 38 # 39 # # def __iter__(self): 40 # # pass 41 # 42 # def __next__(self): 43 # print(‘return from MyIterator::__next__‘) 44 # if len(self.iterable.names) > self.__ind: 45 # ret = self.iterable.names[self.__ind] 46 # self.__ind += 1 47 # return ret 48 # else: 49 # raise StopIteration 50 51 52 def main(): 53 iterable = MyIterable() 54 iterable.add(‘python‘) 55 iterable.add(‘cpp‘) 56 iterable.add(‘csharp‘) 57 58 # iterator = MyIterator() 59 60 # print(isinstance(iterable, Iterable)) 61 # print(isinstance(iterator, Iterator)) 62 63 # print(next(iterator)) 64 65 for name in iterable: 66 print(name) 67 time.sleep(1) 68 69 70 if __name__ == ‘__main__‘: 71 main()
以上是关于Python之迭代器的主要内容,如果未能解决你的问题,请参考以下文章