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

print("done")





Here's the same thing written as a generator:

def squares():
    i = 1
    while True:
        yield i**2
        i += 1


Four lines, versus eight. The iterator version has a lot of boilerplate
(although some of it, the two-line __iter__ method, could be eliminated if
there was a standard Iterator builtin to inherit from).

--
DaveA
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to