Generator question

V

Victor Eijkhout

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.
 
E

Emile van Sebille

On 12/22/2010 3:15 PM Victor Eijkhout said...
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):

How about change to

def __init__(self, data=generator()):
self.data = # the next thing from generator

then...

self.data = data.next()# the next thing from generator

HTH,

Emile
 
D

Dan Stromberg

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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top