7

I know I must be missing something simple, but I am not seeing it.

If I have a generator expression like this:

>>> serializer=(sn for sn in xrange(0,sys.maxint))

I can generate, easily, individual integers like this:

>>> serializer.next()
0
>>> serializer.next()
1
>>> serializer.next()
2

If I write a generator like this:

>>> def ser():
...    for sn in xrange(0,100000):
...       yield sn

It is no bueno:

>>> ser().next()
0
>>> ser().next()
0
>>> ser().next()
0

??? What am I missing ???

4

3 回答 3

21

ser() creates the generator. So each time you call ser() it is sending you a new generator instance. You need to use it just like the expression:

serializer = ser()
serializer.next()

Consider that, if it didn't work this way, you could only ever use the ser() function once and you could never reset it. Plus, you can change the ser function to accept a max integer, and make your program more flexible.

def ser(n=sys.maxint):
    for sn in xrange(0, n):
        yield sn
于 2012-06-09T05:58:14.130 回答
5

In your second example you keep creating a new instance, starting with a fresh generator.

g = ser()
g.next()
g.next()

Create the generator once and reuse it.

于 2012-06-09T05:58:33.757 回答
4
ser()

initializes a new generator each time.

To fix it do something like this:

s = ser()
next(s) # next is preferred over .next which is why .next has been removed in Py3
next(s)
于 2012-06-09T05:57:52.990 回答