yield的优势是可以实时将递归的值反馈回来,形成生成器。
上代码:
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 9 09:16:02 2018
@author: mz
"""
class Sum(object):
def add(self,a, b):
return a +b;
def foreach(self):
for i in range(4):
n = yield i
print("i %d" %(i))
print(n)
if __name__ == "__main__":
s = Sum();
print(s.add(3,5))
lst = s.foreach();
for l in lst:
print(l)
运行结果:
8
0
i 0
None
1
i 1
None
2
i 2
None
3
i 3
None
通过上述结果序列,可以看出:
1 首先返回值
2 执行 yield 下一条语句。打印i
3 n 为None