Finally figured out member generators...

Steven Taschuk staschuk at telusplanet.net
Mon Mar 3 22:11:44 CET 2003


Quoth Bjorn Pettersen:
> In case anyone else has struggled to make their class iterable by making
> a generator produce the individual items...
  [...]
> Example:
>    class Range10:
>        def __init__(self): self.scale = 5
>        def __iter__(self):
>            return Range10.generateItems(self)
>        def generateItems(self):
>            for i in range(10): yield i * self.scale
  [...]

Why is the Range10.generateItems(self) dance necessary?  (I didn't
follow your explanation in the part I snipped.)  The obvious code
seems to work fine:

    >>> from __future__ import generators
    >>> class spam:
    ...     def __iter__(self):
    ...         return self.generateItems()
    ...     def generateItems(self):
    ...         for i in range(10):
    ...             yield 5*i
    ... 
    >>> s = spam()
    >>> s.generateItems
    <bound method spam.generateItems of <__main__.spam instance at 0x8115de4>>
    >>> iter(s)
    <generator object at 0x814e228>
    >>> [x for x in s]
    [0, 5, 10, 15, 20, 25, 30, 35, 40, 45]

Am I misunderstanding something?

-- 
Steven Taschuk                            staschuk at telusplanet.net
Every public frenzy produces legislation purporting to address it.
                                           (Kinsley's Law)





More information about the Python-list mailing list