In article <mailman.372.1427809109.10327.python-l...@python.org>, Dave Angel <da...@davea.name> wrote: >On 03/31/2015 09:18 AM, Albert van der Horst wrote: >> In article <55062bda$0$12998$c3e8da3$54964...@news.astraweb.com>, >> Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > >>> >>> The biggest difference is syntactic. Here's an iterator which returns a >>> never-ending sequence of squared numbers 1, 4, 9, 16, ... >>> >>> class Squares: >>> def __init__(self): >>> self.i = 0 >>> def __next__(self): >>> self.i += 1 >>> return self.i**2 >>> def __iter__(self): >>> return self >> >> You should give an example of usage. As a newby I'm not up to >> figuring out the specification from source for >> something built of the mysterious __ internal >> thingies. >> (I did experiment with Squares interactively. But I didn't get >> further than creating a Squares object.) >> > >He did say it was an iterator. So for a first try, write a for loop: > >class Squares: > def __init__(self): > self.i = 0 > def __next__(self): > self.i += 1 > return self.i**2 > def __iter__(self): > return self > >for i in Squares(): > print(i) > if i > 50: > break >
This is what I get: / -------------------------- albert@cherry:/tmp$ more aap.py class Squares: def __init__(self): self.i = 0 def __next__(self): self.i += 1 return self.i**2 def __iter__(self): return self albert@cherry:/tmp$ python Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from aap import * >>> for i in Squares(): ... print i ... if i>50: break ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: instance has no next() method >>> / -------------------------- Probably not what is intended. Last minute note: renaming __next__() into next() did the job. >-- >DaveA Groetjes Albert -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst -- https://mail.python.org/mailman/listinfo/python-list