grocery_stocker said:
yeah, sorry, i was in a rush and not thinking straight. andrew
Okay, I was thinking more about this. I think this is also what is
irking me. Say I have the following..
a = [1,2,3,4]
for x in a:
... print x
...
1
2
3
4
Would 'a' somehow call __iter__ and next()? If so, does python just
perform this magically?
The for loop calls the __iter__() method to get an iterator object and
then calls the next() method of the iterator object repeatedly to get
the values.
Sometimes you want to give an existing iterator to the for loop; for
that reason iterator objects (can) have an __iter__() method which just
returns the object itself.
For example:
The 'list' class has the __iter__() method:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append',
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']
The __iter__() method returns a 'listiterator' instance:
>>> i = iter([])
>>> type(i)
<type 'listiterator'>
The 'listiterator' class also has the __iter__() method:
['__class__', '__delattr__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__iter__',
'__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next']
which just returns itself:
True