擅长:python、mysql、java
<p>您的<code>if</code>分支没有返回任何</em>,因此您总是在此时到达<code>raise StopIteration</code>。假设<code>low</code>是2,<code>high</code>是10:</p>
<pre><code>if self.low <= self.high: # true, 2 <= 10
if (self.low % 2) == 0: # true, 2 is even
self.low += 1
# else branch is skipped, so we come to the next line
raise StopIteration # iterator ends
</code></pre>
<p>您需要在<code>__next__</code>中创建更大的步骤,因为该方法总是返回一些东西。当一个数字是偶数时,您不必返回,而是需要返回序列中的下一个数字,因此每次递增<code>self.low</code>2,第一次请确保从奇数开始:</p>
^{pr2}$
<p>我在这里对<code>StopIteration</code>条件进行了反向测试,以便更清楚地表明,当仍有值可从iterable返回时,函数总是返回某些内容。在</p>
<p>只是为了重新迭代,<code>__next__</code><strong>总是</strong>返回一些东西,你不能期望它不返回某些东西,所以它至少会<em>返回<code>None</code>。迭代器<em>不计数</em>。Python不去<em>让我们先询问1的结果,然后是2的结果,然后是3的结果</em>。Python只询问奇数序列中的下一个值是什么。1之后是3,但是Python不知道,<strong>您的代码需要生成它</strong>。在</p>