如果在python的类中定义了__next__()和__iter__()方法,生成的实例对象可以通过遍历来取
class Test:
def __init__(self, num, flower):
self.num = num
self.flower = flower
self.dict = dict()
self.getDict()
def getDict(self):
for n, f in zip(self.num, self.flower):
self.dict[n] = f
def __iter__(self):
self.index = 1
return self
def __next__(self):
while True:
try:
flowername = self.dict[self.index]
except:
raise StopIteration
self.index += 1
return flowername
num = [1, 2, 3, 4, 5]
flower = ['琼花', '玉茗', '叠罗金', '蓬莱紫', '玉玲珑']
test = Test(num, flower)
for item in test:
print(item)
输出结果:
琼花
玉茗
叠罗金
蓬莱紫
玉玲珑