擅长:python、mysql、java
<p>问题源于发电机未正确成型。您将需要一个循环,在更新对象状态以准备<code>yield</code>下一个值时,它是所需的值。简而言之,你只需要在{<cd5>}中用{<cd4>}替换你的{<cd3>}就可以了!此代码适用于我(为了清晰起见,删除了注释代码):</p>
<pre><code>class inclusive_range:
def __init__(self, num):
self._start = 0
self._step = 1
self._stop = num
self._next = self._start
# generator implementation - trying to get this to work
def generator(self):
while self._next < self._stop: # < while instead of if
_r = self._next
self._next += self._step
yield _r
</code></pre>
<p>以及测试:</p>
<pre><code>> for i in inclusive_range(10).generator():
print(i)
0
1
2
3
4
5
6
7
8
9
</code></pre>
<p>快乐编码</p>