title: The Iterator Protocol. Is it Dark Magic?
body: <p>So I've been writing iterators for a while, and I thought that I understood them. But I've been struggling with some issues tonight, and the more I play with it, the more confused I become.</p>
  
  <p>I thought that for an iterator you had to implement <code>__iter__</code> and <code>next</code> (or <code>__next__</code>). And that when you first tried to iterate over the iterator the <code>__iter__</code> method would be called, and then <code>next</code> would be called until an <code>StopIteration</code> was raised.  </p>
  
  <p>When I run this code though</p>
  
  <pre><code>class Iter(object):
  
      def __iter__(self):
          return iter([2, 4, 6])
  
      def next(self):
          for y in [1, 2, 3]:
              return y
  
  iterable = Iter()
  for x in iterable:
      print(x)
  </code></pre>
  
  <p>The output is <code>2 4 6</code>. So <code>__iter__</code> is being called, but not <code>next</code>. That does seem to match with the documentation that I found <a href="https://docs.python.org/2/library/stdtypes.html#iterator-types" rel="nofollow noreferrer">here</a>. But then that raises a whole bunch more questions in my mind.  </p>
  
  <p>Specifically, what's the difference between a container type and iterator if it's not the implementation of <code>next</code>? How do I know before hand which way my class is going to be treated? And most importantly, if I want to write a class where my <code>next</code> method is called when I use <code>for x in Iter()</code>, how can I do that?</p>