[Tutor] __iter__

Kent Johnson kent37 at tds.net
Mon Jan 16 22:33:56 CET 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 ?

Yes, you seem to have it right. Your code is fine IMO.

In many cases it's easier to use a generator than an iterator class. If 
you are using this in real code (as opposed to just trying to understand 
__iter__) you should learn about them. Here is your example with a 
generator:

  >>> def squares(start, stop):
  ...   for i in range(start, stop+1):
  ...     yield i*i
  ...
  >>> for i in squares(1, 5):
  ...   print i,
  ...
1 4 9 16 25

Learn about generators here:
http://www.python.org/doc/2.3.5/whatsnew/section-generators.html

Kent

> 
> class Squares:
>         def __init__(self, start, stop):
>                 self.value = start - 1
>                 self.stop = stop
>         def __iter__(self):
>                 return self
>         def next(self):
>                 if self.value == self.stop:
>                         raise StopIteration
>                 self.value += 1
>                 return self.value ** 2
> 
> 
>>>>from iters import Squares
>>>>for i in Squares(1, 5):
> 
> ...     print i,
> ...
> 1 4 9 16 25
> 
> 
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
> -David Bowie
> 
> "Who dares wins"
> -British military motto
> 
> "I generally know what I'm doing."
> -Buster Keaton
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list