Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #85215
| References | <mat6gt$e4j$1@ger.gmane.org> |
|---|---|
| Date | 2015-02-05 01:32 +1100 |
| Subject | Re: basic generator question |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.18463.1423060351.18130.python-list@python.org> (permalink) |
On Thu, Feb 5, 2015 at 12:23 AM, Neal Becker <ndbecker2@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.
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: basic generator question Chris Angelico <rosuav@gmail.com> - 2015-02-05 01:32 +1100
csiph-web