【8.2】什么是迭代器和可迭代对象
1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from collections.abc import Iterator 5 6 7 class Company: 8 def __init__(self, employee_list): 9 self.employee = employee_list 10 11 def __iter__(self): 12 return MyIterator(self.employee) 13 14 15 class MyIterator(Iterator): 16 def __init__(self, employee_list): 17 self.iter_list = employee_list 18 self.index = 0 19 20 def __next__(self): 21 # 真正返回迭代值的逻辑 22 try: 23 word = self.iter_list[self.index] 24 except IndexError: 25 raise StopIteration 26 self.index += 1 27 return word 28 29 30 if __name__ == '__main__': 31 company = Company(['tom', 'bob', 'jane']) 32 my_itor = iter(company) 33 while True: 34 try: 35 print(next(my_itor)) 36 except StopIteration: 37 print('迭代完成')
tom bob jane 迭代完成
可迭代对象
可以被 for in 遍历的对象
迭代器:
迭代器是一个对象
迭代器只能使用一次
迭代器一定是一个可迭代对象,可迭代对象不一定是一个迭代器,迭代器是一个对象class