Generator question

Dan Stromberg drsalists at gmail.com
Wed Dec 22 18:49:31 EST 2010


On Wed, Dec 22, 2010 at 3:15 PM, Victor Eijkhout <see at sig.for.address> wrote:
> So I have a generator, either as a free function or in a class and I
> want to generate objects that are initialized from the generated things.
>
> def generator():
>        for whatever:
>                yield something
> class Object():
>        def __init__(self):
>                self.data = # the next thing from generator
>
> I have not been able to implement this elegantly. For external reasons
> the following syntax is unacceptable:
>
> for g in generator():
>        ob = Object(g)
>
> I really want to be able to write "Object()" in any location and get a
> properly initialized object.
>
> Hints appreciated.
>
> Victor.
> --
> Victor Eijkhout -- eijkhout at tacc utexas edu
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You likely want a class variable:

#!/usr/bin/python

def generator():
    i = 0
    while True:
        yield i
        i += 1

class Object:
    gen = generator()

    def __init__(self):
        self.data = Object.gen.next()

    def __str__(self):
        return str(self.data)

o1 = Object()
o2 = Object()
o3 = Object()

print o1
print o2
print o3



More information about the Python-list mailing list