101 lines
2.6 KiB
Python
101 lines
2.6 KiB
Python
# 第 1-13 课示例:函数进阶
|
||
#
|
||
# 本文件依次演示:
|
||
# 1. 返回多个结果;
|
||
# 2. 提前返回;
|
||
# 3. 使用 *args 接收任意数量的位置参数;
|
||
# 4. 使用 **kwargs 接收任意数量的关键字参数;
|
||
# 5. 在调用函数时解包列表和字典。
|
||
|
||
|
||
def print_separator():
|
||
"""输出分隔线,让不同示例的结果更容易区分。"""
|
||
print("=" * 30)
|
||
|
||
|
||
def get_agent_summary(agent):
|
||
"""返回 Agent 名称和工具数量。"""
|
||
agent_name = agent["name"]
|
||
tool_count = len(agent.get("tools", []))
|
||
return agent_name, tool_count
|
||
|
||
|
||
def get_agent_status(agent):
|
||
"""根据 Agent 的 enabled 配置返回中文状态。"""
|
||
# get() 的第二个参数 False 是默认值。
|
||
# 如果字典中没有 enabled,就把它当作未启用处理。
|
||
if not agent.get("enabled", False):
|
||
return "停用"
|
||
|
||
# 前面的条件成立时,函数已经提前结束。
|
||
# 因此执行到这里时,可以确定 Agent 已经启用。
|
||
return "启用"
|
||
|
||
|
||
def count_tools(*tools):
|
||
"""返回调用者传入的工具数量。"""
|
||
# tools 在函数内部是元组,可以使用 len() 统计元素数量。
|
||
return len(tools)
|
||
|
||
|
||
def build_agent_config(**config):
|
||
"""把关键字参数收集成 Agent 配置字典并返回。"""
|
||
# config 在函数内部是字典。
|
||
return config
|
||
|
||
|
||
def add_three_numbers(first, second, third):
|
||
"""返回三个数字的和。"""
|
||
return first + second + third
|
||
|
||
|
||
def describe_agent(name, model):
|
||
"""返回包含 Agent 名称和模型的描述文本。"""
|
||
return f"{name} 使用 {model}"
|
||
|
||
|
||
print("一、返回多个结果")
|
||
example_agent = {
|
||
"name": "代码助手",
|
||
"tools": ["搜索", "终端"],
|
||
}
|
||
agent_name, tool_count = get_agent_summary(example_agent)
|
||
print(f"Agent 名称:{agent_name}")
|
||
print(f"工具数量:{tool_count}")
|
||
|
||
print_separator()
|
||
|
||
print("二、提前返回")
|
||
print(get_agent_status({"name": "代码助手", "enabled": True}))
|
||
print(get_agent_status({"name": "聊天助手", "enabled": False}))
|
||
|
||
print_separator()
|
||
|
||
print("三、任意数量的位置参数")
|
||
available_tool_count = count_tools("搜索", "终端", "计算器")
|
||
print(f"工具数量:{available_tool_count}")
|
||
|
||
print_separator()
|
||
|
||
print("四、任意数量的关键字参数")
|
||
agent_config = build_agent_config(
|
||
name="代码助手",
|
||
model="gpt-5",
|
||
enabled=True,
|
||
)
|
||
print(agent_config)
|
||
|
||
print_separator()
|
||
|
||
print("五、调用时解包数据")
|
||
numbers = [10, 20, 30]
|
||
total = add_three_numbers(*numbers)
|
||
print(f"数字总和:{total}")
|
||
|
||
agent_data = {
|
||
"name": "代码助手",
|
||
"model": "gpt-5",
|
||
}
|
||
description = describe_agent(**agent_data)
|
||
print(description)
|