7stud said:
repeatedly calls....[type(_t).next(t)]
As far as I can tell, if the call was actually _t.next(), the code I
asked about would work. However, the name look up for 'next' when you
All of your following lamentations are predicated on this assumption, it
would seem. Very well, let's put it to the text, as Python makes it so
easy..:
.... yield 23
.... .... print _t.next()
....
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
<generator object at 0x7c080>
See? a loop that calls _t.next() and only terminates when that raises
StopIteration will never exit when _t.next is a generator function (as
opposed to *the result of calling* a generator function, which is an
*iterator object*). This applies when _t.next is looked up on the
instance, as we ensured we were in this toy example, just as much as
when it's coming from type(_t) -- which is why in this context the
distinction is pedantic, and why it was definitely not crucial, as you
appear (on the basis of this false idea you have) to think it was, in
the Nutshell (where I went for readability rather than pedantic
precision in this instance).
If you want to implement a class whose next method internally uses a
generator, that's pretty easy, e.g.:
class sane(object):
def __init__(self, sentence='four scores and twenty years ago'):
def agenerator():
for word in sentence.split(): yield word
self._thegen = agenerator()
def __iter__(self): return self
def next(self): return self._thegen.next()
there -- easy, innit? You just have to understand the difference
between calling a generator function, and calling the next method of the
object (iterator) which is returned by that function when called
.
Alex