什么是迭代器协议?
对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个stopiteration异常,以终止迭代(只能往后走不能往前进)
可迭代对象:实现了迭代器协议的对象(如何实现:对象内部定义一个iter()方法)
协议是一种约定,可迭代对象实现了迭代器协议,Python的内部工具(如for循环,sum,min,max函数等)使用迭代器协议访问对象。
Python中强大的for循环机制
例如字符串、列表、元组、字典、集合、文件对象等都不是可迭代对象,只不过在for循环时,调用了他们内部的_iter_方法,把他们变成了可迭代对象
然后for循环调用可迭代对象的_next_方法去取值,而且for循环会捕捉Stopiteration异常,以终止迭代。
含有__iter__方法的就是可迭代对象
#__iter__()生成可迭代对象,返回一个对象地址。之后利用__next__()进行遍历 x=‘hello‘ iter_test=x.__iter__() print(iter_test) -----> <str_iterator object at 0x000001AEE54225C0> print(iter_test.__next__()) h print(iter_test.__next__()) e print(iter_test.__next__()) l print(iter_test.__next__()) l print(iter_test.__next__()) 0 l=[1,2,3] for i in l: # i_l=l.__iter__() i_l.__next__() print(i) ====>> 1 2 3 #__iter__()遵循迭代器协议,生成可迭代对象 iter_l=l.__iter__() print(iter_l.__next__()) print(iter_l.__next__()) =====>> 1 2 #不使用for循环,完成元组、列表等等的遍历,while不能进行字典集合的遍历 l=[1,2,3,4] index=0 while index<len(l): print(l[index]) index+=1
#字典 使用for循环得到的是key值,因为for循环本质就是调用下面的 dic={‘a‘:1,‘b‘:2} iter_d=dic.__iter__() print(iter_d.__next__()) ---- > a print(iter_d.__next__()) ---- > b
原文:https://www.cnblogs.com/xtznb/p/10794828.html