python yield 会什么打印none?
看一个小例子:
cat test.py
def gen1(): for i in range(10): x = yield i print("x=%s" % x)
这段代码执行结果如下:
>>> import test as t >>> g=t.gen1() >>> next(g) 0 >>> next(g) x=None 1 >>> next(g) x=None 2 >>> next(g) x=None 3
从例子可看出:
1.生成器方法的每次调用,执行到yield就结束了,并返回yield之后的值。
2.yield本身作为表达式,只返回None,所以x一直打印None
这导致一个疑问,如果我希望x记录上次的保留值需要怎么操作?
def gen3(): for i in range(10): x = i yield i print("x=%s" % x)
这段代码的打印结果就变成了:
>>> import test as t >>> g=t.gen3() >>> next(g) 0 >>> next(g) x=0 1 >>> next(g) x=1 2 >>> next(g) x=2 3
>>> import test as t>>> g=t.gen1()>>> next(g)0>>> next(g)x=None1>>> next(g)x=None2>>> next(g)x=None3