在这段代码中,我有一个类名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)
您的迭代器已经引发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