>>> a =foo() a =foo() >>> a a <generator object foo at 0x1089a5e60> >>> a.next() a.next() start... >>> a.next() a.next() end... Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
第二种:
1 2 3 4
deffoo(): print"start..." yield5 print"end..."
1 2 3 4 5 6 7 8 9 10 11 12 13
a = foo() a = foo() >>> a.next() a.next() start... 5 >>> a.next() a.next() end... Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
第三种:
1 2 3 4 5
deffoo(): print"start..." n = yield5 print n print"end..."
1 2 3 4 5 6 7 8 9 10 11 12 13 14
a = foo() a = foo() >>> a.next() a.next() start... 5 >>> a.send(6) a.send(6) 6 end... Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
总结
实际上,你会发现yield就是你暂停的地方,看第一种没有任何参数也能完成暂停,而 m = yield n而言,n就是你调用生成器的返回值(对外),而m就是你send进来的值(对内)。 我一般形象的将yield成为“暂停到表达式中间”,意思是对于yield这样一个表达式,代码执行到yield,会暂停到这里,并将n返回给调用者,然后在下一次“触发”,才会设置m的值,但这前提是你是用send进行触发的,如果是用next进行触发,那么m的值就会是None。