<p>下面是我在教授Python类时使用的解释:</p>
<p>ITERABLE是:</p>
<ul>
<li>可以循环的任何内容(即可以循环字符串或文件)或</li>
<li>可以出现在for循环右侧的任何内容:<code>for x in iterable: ...</code>或</li>
<li>可以用<code>iter()</code>调用的任何返回迭代器的函数:<code>iter(obj)</code>或</li>
<li>一个定义<code>__iter__</code>的对象,它返回一个新的迭代器,
或者它可能有一个适合索引查找的<code>__getitem__</code>方法。</li>
</ul>
<p>迭代器是一个对象:</p>
<ul>
<li>在迭代过程中记住它在哪里的状态</li>
<li>使用<code>__next__</code>方法:
<ul>
<li>返回迭代中的下一个值</li>
<li>更新状态以指向下一个值</li>
<li>通过提高<code>StopIteration</code>来发出信号</li>
</ul></li>
<li>这是自iterable(意味着它有一个返回<code>__iter__</code>的<code>self</code>方法)。</li>
</ul>
<p>注:</p>
<ul>
<li>Python 3中的<code>__next__</code>方法在Python 2中拼写为<code>next</code>,并且</li>
<li>内置函数<code>next()</code>对传递给它的对象调用该方法。</li>
</ul>
<p>例如:</p>
<pre><code>>>> s = 'cat' # s is an ITERABLE
# s is a str object that is immutable
# s has no state
# s has a __getitem__() method
>>> t = iter(s) # t is an ITERATOR
# t has state (it starts by pointing at the "c"
# t has a next() method and an __iter__() method
>>> next(t) # the next() function returns the next value and advances the state
'c'
>>> next(t) # the next() function returns the next value and advances
'a'
>>> next(t) # the next() function returns the next value and advances
't'
>>> next(t) # next() raises StopIteration to signal that iteration is complete
Traceback (most recent call last):
...
StopIteration
>>> iter(t) is t # the iterator is self-iterable
</code></pre>