0

在这段代码中,我有一个类名 Iter,它包含两个 dunder 方法__iter____next__. 在__iter__方法中,我设置self.current为零并返回self。在下一个方法中,我增加了 self.current += 1. 当它达到 10 时,我希望它引发StopIteration异常。

class Iter:
    def __iter__(self):
        self.current = 0
        return self
        
    def __next__(self):
        self.current += 1
        if self.current == 10:
            raise StopIteration
        
        return self.current
        
it = Iter()
for i in it:
    print(i)
4

1 回答 1

4

您的迭代器已经 raise StopIteration,它被for循环捕获以停止迭代。这就是for循环正常工作的方式。

如果添加以下内容,您可以在迭代器中轻松看到这一点print

    def __next__(self):
        self.current += 1
        if self.current == 10:
            print("raising StopIteration")
            raise StopIteration
1
2
3
4
5
6
7
8
9
raising StopIteration

如果您想在迭代器耗尽后重新引发StopIteration,一种选择是在for循环后手动引发:

it = Iter()
for i in it:
    print(i)
raise StopIteration
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    raise StopIteration
StopIteration

另一个是改变你进行迭代的方式,以便StopIteration不被捕获:

it = iter(Iter())
while True:
    print(next(it))
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print(next(it))
  File "test.py", line 9, in __next__
    raise StopIteration
StopIteration
于 2022-02-12T17:33:03.247 回答