1. 带有 yield 的函数在 Python 中被称之为 generator(生成器) ;
2. 在函数中,当yield语句作为表达式使用,该函数成为协程;
实例一:
def demo():
print("Ready to go!")
while True:
result = (yield)
print(result,type(result))
a = demo()
a.__next__()
a.send("456")
a.send([1,2,3])
a.close()
实例二:
def line_splitter(delimiter=None):
print("Ready to split")
result = None
while True:
line = (yield result)
result = line.split(delimiter)
a = line_splitter(",")
a.__next__()
print(a.send("4,1,2,5,3"))
print(a.send("A,B,C,D,E"))
a.close()