[Tutor] __iter__

Kent Johnson kent37 at tds.net
Tue Jan 17 12:32:31 CET 2006


Danny Yoo wrote:
> 
> 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
> ################################

One small correction: Pointer should have an __iter__() method that 
returns self; this is part of the iterator protocol. See PEP 234
http://www.python.org/peps/pep-0234.html

Kent



More information about the Tutor mailing list