可迭代对象、迭代器和生成器
可迭代对象和迭代器:
1 """ 2 可迭代对象包括迭代器、序列(字符串、列表、元组)和字典 3 可迭代对象:要么实现__iter__方法,返回该可迭代对象的迭代器类实例,要么实现了__getitem__方法,并且参数是从零开始的索引 4 迭代器:实现了__iter__方法,返回迭代器本身,且实现了__next__方法,返回下一个元素,若没有元素抛出StopIteration异常 5 """ 6 7 8 class MyList(object): # 定义可迭代对象类(__iter__方法) 9 def __init__(self, num): 10 self.data = num 11 12 def __iter__(self): 13 return MyListIterator(self.data) # 返回该可迭代对象的迭代器类实例 14 15 16 class MyListIterator(object): # 定义迭代器类(__iter__方法和__next__方法) 17 def __init__(self, data): 18 self.data = data 19 self.now = 0 20 21 def __iter__(self): 22 return self # 返回迭代器本身 23 24 def __next__(self): 25 while self.now < self.data: 26 self.now += 1 27 return self.now-1 # 返回下一个元素 28 raise StopIteration 29 30 31 def main(): 32 my_list = MyList(5) 33 print(type(my_list)) 34 35 my_list_iter = iter(my_list) 36 print(type(my_list_iter)) 37 38 for i in my_list: 39 print(i) 40 41 42 if __name__ == '__main__': 43 main() 44 45 """ 46 结果: 47 <class '__main__.MyList'> 48 <class '__main__.MyListIterator'> 49 0 50 1 51 2 52 3 53 4 54 """
生成器:
1 """ 2 生成器:一种特殊的迭代器,自动实现了“迭代器协议”(__iter__和__next__方法) 3 """ 4 5 6 def my_generator(num): # 定义生成器 7 now = 0 8 while now < num: 9 temp = (yield now) 10 now = now + 1 if temp is None else temp 11 12 13 def main(): 14 my_gen = my_generator(5) 15 print(type(my_gen)) 16 print(dir(my_gen)) # 返回该对象拥有的方法名 17 18 print(next(my_gen)) 19 print(next(my_gen)) 20 21 my_gen.send(3) # 重置当前迭代值 22 print("my_gen.send(3)") 23 print(next(my_gen)) 24 25 26 if __name__ == '__main__': 27 main() 28 29 """ 30 结果: 31 <class 'generator'> 32 ['__class__', '__del__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__next__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw'] 33 0 34 1 35 my_gen.send(3) 36 4 37 """