生成器可以使用的方法:
- next(g)
- g.send(”), 给生成器传递值;
- 给yield所在位置发送一个数据, 直到遇到下一个yield停止.
def fun():
while True:
print("welcome......")
receive = yield "hello"
print(receive)
# ***fun返回值是一个生成器对象.(因为函数中包含yield关键字)
f = fun()
print(f)
print(next(f))
f.send("微信")
def chat_robot():
res = ''
while True:
receive = yield res
if 'age' in receive:
res = "年龄保密"
elif 'name' in receive:
res = "siri"
else:
res = "i don't know what you say"
def main():
# 生成器对象
Robot = chat_robot()
next(Robot)
while True:
send_data = input("粉条>>:")
if send_data == 'q' or send_data == 'bye':
print("不聊了, 我也撤了.....")
break
print(Robot.send(send_data))
main()