【手把手python系列】可迭代对象,迭代器,生成器
1.可迭代对象
1.1可迭代对象定义
使用for进行遍历的对象都是可迭代对象
1.2可迭代对象实现
所有序列类型:list,str,tuple,range;
非序列类型:dict,set,文件对象 f=open(xx,)
实现了__iter__()方法的任意对象(可迭代协议)
实现了__getitem__()方法的任意对象(序列语义)
class MyClass2:
# 实现迭代协议
def __iter__(self):
return iter([11,22,33])
class MyClass:
pass
class MyClass3:
value=[11,22,33]
# 实现序列语义,序列才能索引取值
def __getitem__(self, item):
return self.value[item]
c1=MyClass()
c2=MyClass2()
c3=MyClass3()
for i in c2:
print(i)
for i in c3:
print(i)
for i in c1:
print(i)
Traceback (most recent call last):
File "xxxxx/demo07_可迭代对象.py", line 32, in <module>
for i in c1:
TypeError: 'MyClass' object is not iterable
11
22
33
11
22
33
2.迭代器
2.1迭代器定义
从应用层面上来讲,能够通过for循环进行迭代操作,也能够通过next方法进行迭代操作;
从原理层面上来说,实现了迭代器协议的对象(实现了__inter__方法),也实现了__next__方法。
通过iter()方法,将可迭代对象转换成迭代器
2.2 迭代器的实现
res=iter([11,22,33])
# 迭代操作:
# for循环:迭代循环(循环对一个对象进行迭代操作)
# 内置函数next,可以对迭代器进行迭代操作(内置韩式next本质上是调用的__next__方法进行迭代操作)
r1=next(res)
print(r1)
r2=next(res)
print(r2)
r3=next(res)
print(r3)
# 迭代器中数据迭代完毕之后,迭代器会关闭,如果再次迭代会抛出异常StopIteration
r4=next(res)
print(r4)
11
22
33
Traceback (most recent call last):
File "xxxx/demo08_迭代器.py", line 26, in <module>
r4=next(res)
StopIteration