[Tutor] How to extract numerator and denominator from fractions.Fraction(4, 32)?
Steven D'Aprano
steve at pearwood.info
Tue Aug 6 10:26:35 CEST 2013
On Tue, Aug 06, 2013 at 08:58:31AM +0100, Alan Gauld wrote:
> On 06/08/13 08:16, Jim Mooney wrote:
>
> >> class IterableFraction(Fraction):
> >> def __iter__(self):
> >> yield self.numerator
> >> yield self.denominator
>
> >Seriously, though, I thought yield was like return - one and you're
> >done - how are you getting two yields in there?
>
> yield acts like a return but also a freeze frame.
> So the first time you call the function it runs till it hits yield. The
> next time you call the function it picks up at the yield and continues
> from that point. In this case to the next yield.
All this is correct, but yield is more powerful than that. Not only does
yield get used to return values from a function, it also gets used to
send values *into* a running function.
py> def cr(): # Co-Routine.
... x = yield()
... while True:
... x = yield(x + 1)
...
py> magic = cr()
py> magic.send(None)
()
py> magic.send(1)
2
py> magic.send(2)
3
py> magic.send(99)
100
py> magic.send(3)
4
Prepare to have your mind expanded, possibly until it leaks out your
ears :-)
--
Steven
More information about the Tutor
mailing list