Python异常迭代器

2024-10-03 04:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我以前学过,当程序中有不正常的东西时,应该触发异常。例如,读取文件时出错。 如果您查看这段python代码,您将看到一个stopieration异常被触发。但这并不是该计划的反常行为。所以我的问题是:我们应该在这种情况下提出例外吗?谢谢

class MyIterator():
    def __init__(self, n):
        self.max = n

    def __iter__(self):
        self.count = 0
        return self

    # For Python3
    def __next__(self):
        if self.count == self.max:
            raise StopIteration
        self.count += 1
        return self.count - 1

c = MyIterator(4)
for i in c:
   print(i)

Tags: 文件代码self程序returninitdefcount
2条回答

是的。您不仅应该在此处引发异常,而且还必须在此处引发异常。This is what the iterator protocol calls for

iterator.__next__()

Return the next item from the container. If there are no further items, raise the StopIteration exception. [...]

你是正确的,当程序处于异常状态时应该引发异常(是的,我知道这听起来很多余)。但是,Python中的异常与大多数语言不同。Python中的异常用于核心语言特性,比如迭代,它们比条件语句更受欢迎。Python中常见的习惯用法是"It's easier to ask for foreignness instead of permission"

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

还对^{}语句进行了微调,以允许用户控制异常的处理方式。它允许elsefinally,以及多个except分支与之结合使用。在

是的,当然。当self.count等于self.max时,StopIteration异常需要引发到信号迭代器,这意味着没有更多的元素。看看Python的Iterator documentation

If there are no more elements in the stream, next() must raise the StopIteration exception.

相关问题 更多 >