我以前学过,当程序中有不正常的东西时,应该触发异常。例如,读取文件时出错。 如果您查看这段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)
是的。您不仅应该在此处引发异常,而且还必须在此处引发异常。This is what the iterator protocol calls for:
你是正确的,当程序处于异常状态时应该引发异常(是的,我知道这听起来很多余)。但是,Python中的异常与大多数语言不同。Python中的异常用于核心语言特性,比如迭代,它们比条件语句更受欢迎。Python中常见的习惯用法是"It's easier to ask for foreignness instead of permission":
还对^{} 语句进行了微调,以允许用户控制异常的处理方式。它允许
else
,finally
,以及多个except
分支与之结合使用。在是的,当然。当
self.count
等于self.max
时,StopIteration异常需要引发到信号迭代器,这意味着没有更多的元素。看看Python的Iterator documentation相关问题 更多 >
编程相关推荐