理解python __next__()和__iter__()方法

如果在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)

输出结果:

琼花
玉茗
叠罗金
蓬莱紫
玉玲珑

猜你喜欢

转载自blog.csdn.net/athrunsunny/article/details/121641799