一、迭代器协议
1、迭代器原理:
strtest = "hello"
# for循环遍历机制原理
itertest = strtest.__iter__()
print("使用__iter__函数:", itertest)
print("使用next函数:", itertest.__next__())
print("使用next函数:", itertest.__next__())
print("使用next函数:", itertest.__next__())
print("使用next函数:", itertest.__next__())
print("使用next函数:", itertest.__next__())
# for循环示例(可遍历任意可迭代对象)
for item in strtest:
print("使用for循环遍历:", item)
# while循环示例(只能遍历有序的序列:字符串,元组,列表等有下标的)
index = 0
while index < len(strtest):
print("使用while循环遍历:", strtest[index])
index += 1
注意不要超出迭代器的有序序列的索引: