自定義迭代器對象: 在類里面定義
__iter__和
__next__方法創建的對象就是迭代器對象
iter()函數與next()函數
- iter函數: 獲取可迭代對象的迭代器,會調用可迭代對象身上的__iter__方法
- next函數: 獲取迭代器中下一個值,會調用迭代器對象身上的__next__方法
for循環的本質
遍歷的是可迭代對象
迭代器的作用就是是記錄當前數據的位置以便獲取下一個位置的值
# 自定義迭代器對象: 在類里面定義__iter__和__next__方法創建的對象就是迭代器對象 class MyIterator(object): def __init__(self, my_list): self.my_list = my_list # 記錄當前獲取數據的下標 self.current_index = 0 # 判斷當前對象是否是迭代器 result = isinstance(self, Iterator) print("MyIterator創建的對象是否是迭代器:", result) def __iter__(self): return self # 獲取迭代器中下一個值 def __next__(self): if self.current_index < len(self.my_list): self.current_index += 1 return self.my_list[self.current_index - 1] else: # 數據取完了,需要拋出一個停止迭代的異常 raise StopIteration