一个简单的例子
def test():
i=0
a=4
while i<a:
x=yield i
i+=1
for i in test():
print i
输出
0
1
2
3
不用x也正常
def test():
i=0
a=4
while i<a:
yield i
i+=1
for i in test():
print i
输出同上
用return呢
def test():
i=0
a=4
while i<a:
return i
i+=1
print test()
for i in test():
print i
0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "C:/Python27/Lib/site-packages/xy/temp.py", line 14, in <module>
for i in test():
TypeError: 'int' object is not iterable
函数有返回值,但是不能用for来进行输出了
这是因为协程yield输出的是一个生成器,是一个可迭代对象
举个例子
print range(0,5)
print xrange(0,5)
print type(range(0,5))
print type(xrange(0,5))
输出为
[0, 1, 2, 3, 4]
xrange(5)
<type 'list'>
<type 'xrange'>
next方法
def test():
i=0
a=4
while i<a:
yield i
i+=1
t=test()
print t
print t.next()
print t.next()
print t.next()
print t.next()
print t.next()
输出为
<generator object test at 0x06045B98>
0
1
2
3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "C:/Python27/Lib/site-packages/xy/temp.py", line 21, in <module>
print t.next()
StopIteration
是因为生成器功能用完了,不能再跑,已经StopIteration
def test():
x=yield 3
print "first time%s"%x
x=yield 4
print "first time%s"%x
x=yield 4
print "first time%s"%x
t=test()
for i in t:
print i
print '-----'
输出
3
first timeNone
4
first timeNone
4
first timeNone
发现x没有赋值,意味着函数执行完成之后,生成器是有值的,但是yield并没有为x赋值。
def test():
x=yield 3
print "first time%s"%x
x=yield 4
print "first time%s"%x
x=yield 4
print "first time%s"%x
t=test()
#for i in t:
# print i
print '-----'
print t.next()
print t.send(' try')
print t.send(5)
运行结果如下
-----
3
first time try
4
first time5
4
发现没有使用for循环对生成器进行访问,尽管执行了test函数,但是其迭代行为并没有完成,这时仅仅输出了两个first time,最后的pring并没有执行,而且可以通过send对x进行赋值
当不用send时,仅仅使用next,此时、
def test():
x=yield 3
print "first time%s"%x
x=yield 4
print "first time%s"%x
x=yield 4
print "first time%s"%x
t=test()
#for i in t:
# print i
print '-----'
print t.next()
#print t.send(' try')
#print t.send(5)
输出
-----
3
此时连第一个print都没有执行,仅仅执行了第一个
x=yield 3
语句,这意味着next和send都可以让生产器执行一次迭代,但是也止步于此,并不执行迭代语句之后的语句。
斐波那契数列
def fib(x):
i=1
j=1
while i < x:
yield i
j,i=i+j,j
for i in fib(1000):
print i