码迷,mamicode.com
首页 > 编程语言 > 详细

Python之迭代器

时间:2018-10-21 20:35:30      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:法则   import   实例   iterable   col   ati   turn   lis   +=   

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之迭代器

标签:法则   import   实例   iterable   col   ati   turn   lis   +=   

原文地址:https://www.cnblogs.com/linxmouse/p/9826568.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!