Python 中的迭代器如何工作?

How except works for iterators in Python?

你能给我解释一下为什么示例中从未执行过 except 子句并且从未调用过 print 吗?

def h(lst):
  try:
    yield from lst
  except StopIteration:
    print('ST')

t = h([1,2])
next(t)
>>> 1
next(t)
>>> 2
next(t)
>>> Traceback (most recent call last):

File "<ipython-input-77-f843efe259be>", line 1, in <module>
next(t)

StopIteration

您的 next 调用 您的 h 函数之外,因此不在您的 try / except 子句中.为了比较,试试这个:

def h(lst):
    yield from lst

t = h([1,2])

然后 运行 重复:

try:
    print(next(t))
except StopIteration:
    print('ST')

结果:

1
2
'ST'
'ST'
'ST'
...

StopIterationnext 抛出,而不是由 yield from 抛出:

next(iterator[, default])

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

因此您可以换行 next 调用。

def h(lst):
    yield from lst

def next_or_print(it):
    try:
        next(it)
    except StopIteration:
        print('ST')

然后你这样使用它:

>>> t = h([1,2])
>>> next_or_print(t)
1
>>> next_or_print(t)
2
>>> next_or_print(t)
ST

请注意 next 还有第二个参数,允许提供 default 而不是 StopIteration:

>>> t = h([1,2])
>>> next(t, 'ST')
1
>>> next(t, 'ST')
2
>>> next(t, 'ST')
ST
def h(lst):
  try:
    yield from lst
  except StopIteration:
    print('ST')
t = h([1, 2])
>>> print(t)
<generator object h at 0x7fbf6f08aa40>

函数"h"returns生成器。作为 "return" 的语句 "yield" 什么都不做,只是 returns 一个生成器。异常不会出现在那部分代码中。

异常必须转移到代码的另一部分,它会在那里工作。

def h(lst):
    yield from lst
t = h([1, 2])
next(t)
next(t)
try:
    next(t)
except StopIteration:
    print('ST')
ST