迭代器

迭代器能減小內存空間實現循環。app

方法1:spa

 1 import time
 2 from collections import Iterable
 3 from collections import Iterator
 4 
 5 
 6 class Classmate(object):
 7 
 8 
 9     def __init__(self):
10         self.names = list()
11 
12 
13     def add(self,name):
14         self.names.append(name)
15 
16 
17     def __iter__(self):
18         """若是想要一個對象變成一個能夠迭代的對象,便可以使用for,那麼必須實現__iter__方法"""
19         return Classmator(self);  # 調用Classmator 而後把本身傳過去
20 
21 
22 class Classmator(object):
23     def __init__(self,obj):
24         self.obj = obj
25         # 定義索引值
26         self.current_num = 0
27 
28     def __iter__(self):
29         pass
30 
31 
32     def __next__(self):
33         # 判斷索引值是否超出列表個數範圍
34         if self.current_num < len(self.obj.names):
35             ret = self.obj.names[self.current_num]
36             # 索引值+1
37             self.current_num += 1
38             return ret
39         else:
40             # 拋出異常,終止for循環
41             raise StopIteration
42 
43 classmate = Classmate()
44 
45 classmate.add("張三")
46 classmate.add("張二")
47 classmate.add("李四")
48 
49 # 判斷一個類型是否能夠迭代   isinstance(要判斷的對象,Iterable)
50 print("判斷classmate是不是能夠迭代的對象:", isinstance(classmate,Iterable))
51 # 迭代器
52 classmate_iterator = iter(classmate)
53 # 判斷classmate_iterator是不是迭代器
54 print("判斷classmate_iterator是不是迭代器:", isinstance(classmate_iterator,Iterator))
55 # print(next(classmate_iterator))
56 
57 for name in classmate:
58     print(name)
59     time.sleep(1)

兩個類能夠改善成一個,只要有__iter__方法和__next__方法:code

 1 import time
 2 from collections import Iterable
 3 from collections import Iterator
 4 
 5 
 6 
 7 class Classmate(object):
 8     def __init__(self):
 9         self.names = list()
10         self.current_num = 0
11 
12     def add(self,name):
13         self.names.append(name)
14 
15 
16     def __iter__(self):
17         return self
18 
19 
20     def __next__(self):
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             raise StopIteration
27 
28 
29 classmate = Classmate()
30 classmate.add("張三")
31 classmate.add("李四")
32 classmate.add("王五")
33 
34 # 判斷一個類型是否能夠迭代   isinstance(要判斷的對象,Iterable)
35 print("判斷classmate是不是能夠迭代的對象:", isinstance(classmate,Iterable))
36 # 迭代器
37 classmate_iterator = iter(classmate)
38 # 判斷classmate_iterator是不是迭代器
39 print("判斷classmate_iterator是不是迭代器:", isinstance(classmate_iterator,Iterator))
40 # print(next(classmate_iterator))
41 
42 for name in classmate:
43     print(name)
44     time.sleep(1)
相關文章
相關標籤/搜索