feat(python进阶): 新增模块与包课程
This commit is contained in:
63
02_python进阶/2_1_模块与包/module_example.py
Normal file
63
02_python进阶/2_1_模块与包/module_example.py
Normal file
@@ -0,0 +1,63 @@
|
||||
# 第 2-1 课完整示例:模块与包
|
||||
#
|
||||
# 本文件依次演示:
|
||||
# 1. 使用 import 导入 Python 标准库模块;
|
||||
# 2. 使用 import 导入自己编写的模块;
|
||||
# 3. 使用 from...import... 导入指定内容;
|
||||
# 4. 从自定义包中导入模块;
|
||||
# 5. 使用程序入口判断组织主程序。
|
||||
|
||||
import random
|
||||
|
||||
import agent_tools
|
||||
from agent_tools import build_agent_description
|
||||
from agent_package.status_text import get_status_text
|
||||
|
||||
|
||||
def print_separator():
|
||||
"""输出分隔线,让不同示例更容易阅读。"""
|
||||
print("=" * 30)
|
||||
|
||||
|
||||
def show_standard_library_example():
|
||||
"""演示使用标准库模块生成随机推荐。"""
|
||||
tools = ["搜索", "终端", "计算器"]
|
||||
recommended_tool = random.choice(tools)
|
||||
print(f"随机推荐工具:{recommended_tool}")
|
||||
|
||||
|
||||
def show_custom_module_example():
|
||||
"""演示使用自己编写的 agent_tools 模块。"""
|
||||
tool_count = agent_tools.get_tool_count(agent_tools.DEFAULT_TOOLS)
|
||||
print(f"默认工具:{agent_tools.DEFAULT_TOOLS}")
|
||||
print(f"默认工具数量:{tool_count}")
|
||||
|
||||
description = build_agent_description("代码助手", "gpt-5")
|
||||
print(description)
|
||||
|
||||
|
||||
def show_package_example():
|
||||
"""演示从自定义包中导入并使用函数。"""
|
||||
enabled = True
|
||||
status_text = get_status_text(enabled)
|
||||
print(f"Agent 状态:{status_text}")
|
||||
|
||||
|
||||
def main():
|
||||
"""按照顺序运行本课的三个示例。"""
|
||||
print("一、标准库模块")
|
||||
show_standard_library_example()
|
||||
|
||||
print_separator()
|
||||
|
||||
print("二、自定义模块")
|
||||
show_custom_module_example()
|
||||
|
||||
print_separator()
|
||||
|
||||
print("三、自定义包")
|
||||
show_package_example()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user