【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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM