<p>您的具体问题是,第一个偶数将落到<code>StopIteration</code>行,使您的序列相当短:<code>{ 1 }</code>。在</p>
<p>在我看来,生成所有奇数应该要容易得多。从<code>-1</code>开始,然后在每次呼叫时:</p>
<ul>
<li>加两个。</li>
<li>如果太高了,停下来。</li>
<li>否则返回当前值。</li>
</ul>
<p>可通过以下方式实现:</p>
<pre><code>class Odds:
def __init__(self, arg):
self.num = arg
def __iter__(self):
return OddsIterator(self.num)
class OddsIterator:
def __init__(self, arg):
self.high = arg
self.curr = -1
def __next__(self):
self.curr += 2
if self.curr > self.high:
raise StopIteration
return self.curr
o = Odds(10)
for i in o:
print (i)
</code></pre>
<hr/>
<p>话虽如此,我不确定我是否会像你那样执行它。当您可以将两个独立的类合并为一个类时,似乎没有必要使用它们:</p>
^{pr2}$
<hr/>
<p>此外,还可以通过提供<code>start</code>和<code>step</code>值使其更通用:</p>
<pre><code>class XFor:
def __init__(self, start, end, step):
self.curr = start - step
self.lim = end
self.step = step
def __next__(self):
self.curr += self.step
if self.curr > self.lim:
raise StopIteration
return self.curr
def __iter__(self):
return self
o = XFor(1,10,2)
for i in o:
print (i)
</code></pre>
<p>尽管它很危险地侵犯了<code>range()</code>的功能,所以我还是用它。除非你的目的是自我教育,在这种情况下要玩得开心。在</p>