basic generator question

Joel Goldstick joel.goldstick at gmail.com
Wed Feb 4 10:19:34 EST 2015


On Wed, Feb 4, 2015 at 9:32 AM, Chris Angelico <rosuav at gmail.com> wrote:

> On Thu, Feb 5, 2015 at 12:23 AM, Neal Becker <ndbecker2 at gmail.com> wrote:
> > 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.
>

Can you actually show your code and the traceback?

>
> So, if I understand you correctly, you want your rpt object to return
> 'hello' five times to five consecutive calls?
>
> >>> a = rpt()
> >>> a()
> 'hello'
> >>> a()
> 'hello'
> >>> a()
> 'hello'
> >>> a()
> 'hello'
> >>> a()
> 'hello'
>
> You could do that with a generator by repeatedly calling next() on it,
> or you could just keep track of the number of times you were called:
>
> class rpt:
>   def __init__ (self, value, rpt):
>     self.value = value; self.rpt = rpt
>   def __call__ (self):
>     if self.rpt:
>       self.rpt -= 1
>       return self.value
>    # ... otherwise?
>
> Up to you to figure out what to do when self.rpt hits zero.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150204/a8175834/attachment.html>


More information about the Python-list mailing list