迭代器协议

'''
一、迭代器协议:1,对象必须提供一个next()方法
             2,执行该方法,要么返回迭代中的下一项,要么引起一个StopIteration异常,以终止跌倒
二、可迭代对象,    实现了迭代器协议的对象
三、for循环的本质就是遵循迭代器协议去访问对象
四、字符串,列表,元组,字典,集合,文件这些均不限属于可迭代对象,
    for循环之所以能遵循迭代器协议对其进行访问,实际上是调用了这些对象内的iter()方法,将这些对象变成了可迭代对象
    再通过next()方法·取值,直到取到stopiteration异常时终止迭代,停止循环

'''
# vocaloid_list=['miku','rin','ran','ruka']
# vocaloid=vocaloid_list.__iter__()
# print(vocaloid.__next__())      #输出结果:miku
# print(vocaloid.__next__())      #输出结果:rin
# print(vocaloid.__next__())      #输出结果:ran
# print(vocaloid.__next__())      #输出结果:ruka
# print(vocaloid.__next__())      #报告StopIteration异常

'''
内置函数中的next()函数与__next__()方法的效果是一样的
        next(变量) 《--------》变量.__next__()
        
'''
# vocaloid_list=['miku','rin','ran','ruka']
# vocaloid=vocaloid_list.__iter__()
# print(vocaloid.__next__())      #输出结果:miku
# print(next(vocaloid))           #输出结果:rin
# print(vocaloid.__next__())      #输出结果:ran
# print(vocaloid.__next__())      #输出结果:ruka
# print(vocaloid.__next__())      #报告StopIteration异常

'''

对于有序序列:字符串,列表,元组等虽然可以使用while以下标的方式遍历,
但对于无序的字典集合文件等对象则无法遍历
for循环通过基于迭代器协议访问对象,提供了一个统一的遍历所有对象的方法

'''

'''
通过while模拟for循环的工作方式=
'''
def iteration_while(x):
    temp=x.__iter__()
    while True:
        # result=temp.__next__()
        # if result == 'StopIteration':
        #     print('监测到StopIteration异常,终止循环')
        #     # break
        # else:
        #     print(result)
        try:
            print(temp.__next__())
        except StopIteration:
            print('监测到StopIteration异常,迭代结束')
            break
vocaloid_list = ['miku', 'rin', 'ran', 'ruka']
iteration_while(vocaloid_list)

 

posted @ 2020-06-25 12:17  雑音未来  阅读(151)  评论(0)    收藏  举报