- >>> lst_num = [1,2,3]
- >>> iter = (i for i in lst_num)
- >>> print iter.next
- <method-wrapper 'next' of generator object at 0xb71566e4>
- >>> print iter.next()
- 1
- >>> print iter.next()
- 2
- >>> print iter.next()
- 3
- >>> print iter.next()
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- StopIteration
- >>> def use_yield():
- ... for i in range(10):
- ... yield(i)
- ...
- >>>
- >>> iter = use_yield()
- >>> iter.next()
- 0
- >>> iter.next()
- 1
- >>> iter.next()
- 2
- >>> def use_send():
- ... print 'how are you?',
- ... m = yield('55555')
- ... print m
- ... n = yield('aaaaaaaaaaa')
- ... print 'ok!'
- ...
- >>> test = use_send()
- >>> test.send(None)
- how are you?
- '55555'
- >>> test.next()
- None
- 'aaaaaaaaaaa'
- >>> test.next()
- ok!
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- StopIteration
- >>> test = use_send()
- >>> test.next()
- how are you?
- '55555'
- >>> test.send('fine,3Q.')
- fine,3Q.
- 'aaaaaaaaaaa'
第一个例子是告诉怎么输出generator对象
第2个是使用 yield 产生generator对象
第3个例子涉及到generatorde 原理,
- m = yield('55555')
- 相当于下面伪代码
- print(‘55555’) //输出55555
m = wait_and get() //等待输入,并把值返给m,另外告诉next() = send(None)
详细解释参考http://blog.donews.com/limodou/archive/2006/09/04/1028747.aspx