一、迭代协议:
可以被迭代要满足要求的就叫做可迭代协议。内部实现__iter__方法。
iterable:可迭代的--对应的标志。
什么叫做迭代?:可以一个一个取值,就像for循环一样取值。
字符串,列表,元祖,集合,字典都是也可以迭代的。
二、迭代器协议:内部实现__iter__,__next__方法。
迭代器的优点:节约内存,方便操作。
1 print(dir([1,2]))#查看列表的所有方法 2 print(dir([1,2].__iter__()))#查看列表迭代器的方法 3 print(set(dir([1,2].__iter__()))-set(dir([1,2])))#查看迭代独有的方法
实例:
iter_l = [0,1,2,3,4,5,6,].__iter__() print(iter_l.__length_hint__())#获取迭代器长度 print(iter_l.__setstate__(4))#指定从哪里开始迭代 print(iter_l.__next__())#一个一个取值 输出: 7 None 4
三、可迭代和迭代器的相同点:
都可以用for循环
四、可迭代和迭代器不同点:
迭代器内部多实现了一个__next__方法。
五、判断迭代器和可迭代的方法:
1、判断内部是不是实现了__next__方法
2、iterator判断是不是迭代器
iterable判断是不是可迭代对象