basic generator question
Neal Becker
ndbecker2 at gmail.com
Wed Feb 4 08:23:40 EST 2015
I have an object that expects to call a callable to get a value:
class obj:
def __init__ (self, gen):
self.gen = gen
def __call__ (self):
return self.gen()
Now I want gen to be a callable that repeats N times. I'm thinking, this
sounds perfect for yield
class rpt:
def __init__ (self, value, rpt):
self.value = value; self.rpt = rpt
def __call__ (self):
for i in range (self.rpt):
yield self.value
so I would do:
my_rpt_obj = obj (rpt ('hello', 5))
to repeat 'hello' 5 times (for example).
But this doesn't work. when obj calls self.gen(), that returns a generator, not
the next value.
How can I make this work? I can't change the interface of the existing class
obj, which expects a callable to get the next value.
--
-- Those who don't understand recursion are doomed to repeat it
More information about the Python-list
mailing list