Home > Mobile >  Iterator pattern return infinite objects
Iterator pattern return infinite objects

Time:10-27

Hello I am trying to build a class list based like this

class DummyList(Iterator):
    ...
    def __next__(self) -> int:
        list = [1, 2, 3, 4, 5]
        for i in list:
            yield i

And I am using like this

dl = DummyList()

for i in dl:
    print(i)

The output that I expected was

1
2
3
4
5

But instead I get

12345
12345
12345
....

How can I solve this?

Thanks

CodePudding user response:

This would be the correct way to implement an iterator:

from collections.abc import Iterator


class DummyList(Iterator):
    def __init__(self):
        self.lst = [1, 2, 3, 4, 5]
        self.current = -1

    def __iter__(self):
        return self

    def __next__(self):
        self.current  = 1
        if self.current < len(self.lst):
            return self.lst[self.current]
        raise StopIteration

This is the output:

dl = DummyList()

for i in dl:
    print(i)
1
2
3
4
5
  • Related