Python Iterators: Use of __iter__ method in a class
<p>I have been reading about <a href="https://docs.python.org/2/tutorial/classes.html#iterators" rel="nofollow">Iterators in the python 2.7.x Documentation</a>
The given sample program in the link defines a <code>__iter__</code> method to make the class <em>"iterable"</em>.</p>

<p>However, i cannot find any use of <code>__iter__</code> method defined in the class, i.e. to say- Even if i don't define <code>__iter__</code> , i can still iterate upon the object of the class. </p>

<p>Code 1 # From the documentation</p>

<pre><code>class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
</code></pre>

<p>Code 2 # Except for defining the <strong>iter</strong> method it's the same. </p>

<pre><code>class ReverseMod:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    # Missing __iter__()
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
</code></pre>

<p>Output:</p>

<pre><code>rev = Reverse('spam')
revMod = ReverseMod('spam')

rev.next() #m
rev.next() #a
rev.next() #p
...

revMod.next() #m
revMod.next() #a
revMod.next() #p
...
</code></pre>

<p>Objects from class <strong>Reverse</strong> and <strong>ReverseMod</strong> behave the same way. Only thing is when i do a iter(revMod) it says </p>

<blockquote>
  <p>TypeError: iteration over non-sequence</p>
</blockquote>

<p>Why do i even need to concern myself about doing iter(revMod)? Why do i need to care defining <code>__iter__</code> at all. Seems like i can get the functionalities of doing a <em>.next()</em> without defining <code>__iter__</code> at all.</p>