It also confuse me for a little time :)
ok,let's see a for loop in python:
for i in a:
print i
In this snippet, the for loop will implicitly calls a.iter(),which should be an iterator.What's more ,in python, if you want an iterator ,the class must implement 'the iterator' interface, which means it should have both__iter__ and__next__ , and the effect of __iter__is return an iterator.
However, there is another concept in python that calls iterable,it is a factory which can pruduct iterators.
OK,now,what we want is can iter either iterator or iterable, so, their iter method must return a iterator.
for iterable,it should return an iterator(probably another class implement 'iterator' interface), and for iterator, yeah, itself is an iterator, so just return itself!
the following snippet is copy from Fluent Python:
import reprlib
RE_WORD = re.compile('\w+')
class Sentence:
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self):
return SentenceIterator(self.words)
class SentenceIterator:
def __init__(self, words):
self.words = words
self.index = 0
def __next__(self):
try:
word = self.words[self.index]
except IndexError:
raise StopIteration()
self.index += 1
return word
def __iter__(self):
return self
s = Sentence('"The time has come," the Walrus said,')
you can do:
for i in iter(s):
print(s)
and:
for i in s:
print(s)
if you remove __iter__in iterator,you can only use:
for i in s:
print(s)
Because iter(s) is no more an iterator when you remove __iter__in iterator class