yield 的特点:懒惰、节省、分步yield:干一点活,给你一点结果,歇会儿,等你再要时继续干。特点:
假设你要数1到5:
return(普通方式)def count_to_five():
result = [1, 2, 3, 4, 5] # 先把所有数准备好
return result
numbers = count_to_five()
for n in numbers:
print(n)
[1, 2, 3, 4, 5] 全算出来。yield(生成器方式)def count_to_five():
for i in [1, 2, 3, 4, 5]:
yield i # 每次只给一个数
numbers = count_to_five()
for n in numbers:
print(n)
yield i),然后暂停。1 2 3 4 5,但方式不同。yielddef _invoke(self, tool_parameters: dict[str, Any]):
yield self.create_json_message({"result": "Hello, world!"})
特点体现:
for 循环时才生成这个消息。ToolInvokeMessage,不存多余东西。yield),但如果加更多 yield,会逐步输出。试试看:
tool = MyTestTool()
messages = tool._invoke({"input": "test"}) # 返回生成器
for msg in messages:
print(msg) # 只打印一次,因为只有一个 yield
yield:你代码里只 yield 了一次,看起来跟 return 差不多,所以感觉不出区别。yield:def _invoke(self, tool_parameters: dict[str, Any]):
yield self.create_json_message({"result": "Step 1"})
yield self.create_json_message({"result": "Step 2"})
for msg in tool._invoke({"input": "test"}):
print(msg)
ToolInvokeMessage({"result": "Step 1"})
ToolInvokeMessage({"result": "Step 2"})
List 或 Iterator,但得自己管理。public List<String> invoke() {
return Arrays.asList("Hello, world!"); // 一次性返回
}
Iterator:public Iterator<String> invoke() {
List<String> list = Arrays.asList("Step 1", "Step 2");
return list.iterator(); // 分步,但得先准备好列表
}
yield:不用自己写 Iterator,直接在函数里 yield,自动变成分步返回。yield:你去超市买5个苹果,收银员一次性给你5个,你拿回家。yield:收银员每次给你1个苹果,你拿一个吃一个,吃完再回去拿下一个。试试这个:
def say_hello():
yield "Hi"
yield "there"
for word in say_hello():
print(word)
Hi 和 there,分两行。yield 分两次给了你结果。yield 的特点代码里因为只有一个 yield,所以没发挥出这些特点。如果改成多个 yield,你就会明显感觉到它跟 return 的不同。