[Tutor] __iter__
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Tue Jan 17 02:57:37 CET 2006
On Mon, 16 Jan 2006, Christopher Spears wrote:
> I'm not sure if I understand __iter__. You use it to create an object
> that iterates through itself using a next menthod ?
Hi Chris,
Yes, that's one application.
But __iter__() doesn't necessarily have to return 'self'. For example,
here's a useless toy class that might help explain what can happen if we
do so without thinking:
################################
class MyListOfNumbers:
def __init__(self, data):
self.data = data
def __iter__(self):
return Pointer(self)
class Pointer:
def __init__(self, numbers):
self.numbers = numbers
self.offset = 0
def next(self):
if self.offset == len(self.numbers.data):
raise StopIteration
element = self.numbers.data[self.offset]
self.offset = self.offset + 1
return element
################################
Let's see how this might work:
#######
>>> nums = MyListOfNumbers([0, 1])
>>> for x in nums:
... for y in nums:
... print x, y
...
0 0
0 1
1 0
1 1
#######
Now imagine what might happen if we didn't return a separate Pointer
iterator:
################################################
class MyListOfNumbers2:
def __init__(self, data):
self.data = data
self.offset = 0
def __iter__(self):
return self
def next(self):
if self.offset == len(self.data):
raise StopIteration
element = self.data[self.offset]
self.offset = self.offset + 1
return element
####################################################
On a glance, this also looks reasonable:
######
>>> nums = MyListOfNumbers2([3, 1, 4, 1, 5])
>>> for n in nums:
... print n
...
3
1
4
1
5
######
But, of course, you know that there has to be SOMETHING wrong here.
*grin*
And here's one example that shows a problem:
######
>>> nums = MyListOfNumbers2([0, 1])
>>> for x in nums:
... for y in nums:
... print x, y
...
0 1
>>>
######
We expected to see all pairs of 0-1 combinations, but came up way short.
Do you know why?
Best of wishes!
More information about the Tutor
mailing list