How to create a class as an iterator with stop point in Python

1 Answer

0 votes
class Test:
    def __iter__(self):
        self.n = 1
        return self

    def __next__(self):
        if self.n <= 13:
            val = self.n
            self.n += 1
            return val
        else:
            raise StopIteration

o = Test()
it = iter(o)

for i in it:
    print(i)


'''
run:

1
2
3
4
5
6
7
8
9
10
11
12
13

'''

 



answered Nov 24, 2018 by avibootz
...