1 from collections import Iterable
2 from collections import Iterator
3 import time
4
5 class Classmate(object):
6
7 def __init__(self):
8 self.names = list()
9 self.current_num = 0
10
11 def add(self,name):
12 self.names.append(name)
13
14 #判断类是否是迭代器,需要有__iter__和__next__方法
15 def __iter__(self):
16 return self
17
18 def __next__(self):
19
20 #遍历列表names的数据,以current_num计算
21 if self.current_num < len(self.names):
22 ret = self.names[self.current_num]
23 self.current_num += 1
24 return ret
25 else:
26 #如果迭代器循环结束后,抛出停止迭代器异常
27 raise StopIteration
28
29 #创建迭代器类的对象并添加数据
30 classmate = Classmate()
31 classmate.add("one")
32 classmate.add("two")
33 classmate.add("three")
34
35 #使用类的迭代器
36 for name in classmate:
37 print(name)
38 time.sleep(1)