一、构建一个可迭代对象(列表、元组、字典等)
#tuple01、dict01自带有__iter__属性,即为可迭代对象
tuple01 = ("Stay hungry Stay foolish","Keep looking,don't sate","hobbies")
dict01 = {"Steve Jobs":1001,"Bill Gates":1002,"near Object":1003}
二、用for循环来进行迭代
(1). 代码如下所示:
for tuple01_i in tuple01:
print(tuple01_i)
# for dict01_i in tuple01:
# print(dict01_i)
(2). 结果如下:
Stay hungry Stay foolish
Keep looking,don't sate
hobbies
三、使用for循环底层原理来进行迭代
(1). 代码如下所示:
# 1.获取可迭代对象的迭代器
# iterator = tuple01.__iter__()
iterator = dict01.__iter__()
while True:
try:
# 2.使用迭代器取所有的下一个元素并显示
item = iterator.__next__()
# print(item)
print(item+":",dict01[item])
# 3.遇到异常停止迭代
except StopIteration:
break
(2). 结果如下:
Steve Jobs: 1001
Bill Gates: 1002
near Object: 1003
四、用for循环以及其底层原理来迭代图形类对象
(1). 代码如下所示:
#encoding = utf-8
"""
@version:3.7
@author:qiu
@file:iter_demo.py
@time:23:18
"""
class Graphical: #图形类
pass
class GraphicalManager: #图像管理器类
def __init__(self):
self.__graphs = []
def add(self,graph):
self.__graphs.append(graph)
# 1.创建可迭代对象,有__iter__方法就是可迭代对象
def __iter__(self):
return GradphicalIterator(self.__graphs)
class GradphicalIterator: #图形迭代器类
def __init__(self,graphs):
self.__graphs = graphs
self.__index = -1
def __next__(self): #2.创建迭代器,有__next__方法就是迭代器
self.__index += 1
if self.__index > len(self.__graphs) - 1:
raise StopIteration #3.迭代完所有图形后,停止迭代
return self.__graphs[self.__index]
graph_m = GraphicalManager()
graph_m.add(Graphical())
graph_m.add(Graphical())
graph_m.add(Graphical())
#for循环遍历所有图像类对象
for graphical_i in graph_m:
print("1.图像对象:",graphical_i)
#for循环底层原理遍历所有图像类对象
iterator = graph_m.__iter__()
while True:
try:
item = iterator.__next__()
print("2.图形对象:",item)
except StopIteration:
break
(2). 结果如下:
1.图像对象: <__main__.Graphical object at 0x0000016F03B42F08>
1.图像对象: <__main__.Graphical object at 0x0000016F03B42F48>
1.图像对象: <__main__.Graphical object at 0x0000016F03B42F88>
2.图形对象: <__main__.Graphical object at 0x0000016F03B42F08>
2.图形对象: <__main__.Graphical object at 0x0000016F03B42F48>
2.图形对象: <__main__.Graphical object at 0x0000016F03B42F88>