回调函数(Callback Function)或回调方法(Callback Method)是编程中的一种重要概念,广泛应用于各种编程语言和框架中,包括Python。它们允许程序在特定事件发生时执行预定义的代码,从而实现灵活和可扩展的程序设计。
1. 什么是回调函数/方法
回调函数是作为参数传递给另一个函数的函数。当某个特定事件发生或某个条件满足时,这个被传递的函数(即回调函数)会被调用执行。
回调方法与回调函数类似,但通常指的是对象的方法作为回调被调用。
2. 回调函数的工作原理
回调函数的核心思想是将一个函数(回调)作为参数传递给另一个函数。在适当的时候,调用方函数会执行这个回调函数。这种机制使得代码更加灵活,允许不同的行为在不同的情况下被触发。
3. 回调函数的用途
- 事件处理:在图形用户界面(GUI)编程中,回调函数用于响应用户的操作,如点击按钮、移动鼠标等。
- 异步编程:在处理异步任务(如网络请求、文件读取等)时,回调函数用于在任务完成后处理结果。
- 自定义行为:允许用户定义特定的行为,以适应不同的需求。
4. 回调函数的优点
- 提高代码的灵活性:通过回调函数,可以在不修改核心逻辑的情况下,改变或扩展程序的行为。
- 实现解耦:回调机制使得代码的不同部分之间耦合度降低,提高了代码的可维护性和可重用性。
- 支持异步操作:在处理异步任务时,回调函数提供了一种处理结果的方法,使得程序不会被阻塞。
5. 回调函数的示例
示例 1:简单的回调函数
def greet(name):
print(f"Hello, {name}!")
def process_user(name, callback):
# 这里可以添加一些处理逻辑
callback(name)
# 使用回调函数
process_user("Alice", greet)
输出:
Hello, Alice!
在这个例子中,greet
函数作为回调被传递给 process_user
函数。当 process_user
执行时,它调用了传入的回调函数 greet
,并传递了参数 "Alice"
。
示例 2:异步回调
import time
import threading
def long_running_task(callback):
def task():
print("任务开始...")
time.sleep(2) # 模拟长时间运行的任务
print("任务完成!")
callback("任务结果")
thread = threading.Thread(target=task)
thread.start()
def handle_result(result):
print(f"回调接收到: {result}")
# 启动长时间运行的任务,并提供回调函数
long_running_task(handle_result)
输出:
任务开始...
任务完成!
回调接收到: 任务结果
在这个例子中,long_running_task
函数启动了一个新的线程来执行一个耗时的任务。任务完成后,它调用传入的回调函数 handle_result
并传递结果。
6. 回调方法的示例
回调方法通常在面向对象编程中使用,尤其是在继承和多态的场景下。
from abc import ABC, abstractmethod
class EventHandler(ABC):
@abstractmethod
def on_event(self, data):
pass
class PrintEventHandler(EventHandler):
def on_event(self, data):
print(f"事件触发,数据: {data}")
def trigger_event(handler, data):
handler.on_event(data)
# 使用回调方法
handler = PrintEventHandler()
trigger_event(handler, "示例数据")
输出:
事件触发,数据: 示例数据
在这个例子中,EventHandler
是一个抽象基类,定义了一个抽象方法 on_event
。PrintEventHandler
继承自 EventHandler
并实现了 on_event
方法。trigger_event
函数接收一个 EventHandler
对象,并在事件触发时调用其 on_event
方法。
7. 实际应用中的回调
在实际开发中,回调函数和方法广泛应用于各种框架和库中。例如:
- Flask/Django 等Web框架:路由处理函数就是一种回调函数,用于处理特定的HTTP请求。
- Tkinter 等GUI库:按钮点击事件绑定的回调函数用于响应用户操作。
- 异步库如 asyncio:回调函数用于在异步任务完成时处理结果。
8. 注意事项
- 回调地狱(Callback Hell):当多个回调函数嵌套使用时,代码会变得难以阅读和维护。这时可以考虑使用更高级的异步编程方法,如
async/await
。 - 错误处理:在回调函数中处理错误时需要小心,确保异常不会导致整个程序崩溃。
- 性能:过多的回调函数可能会影响程序的性能,尤其是在高频调用的场景下。
9. 总结
回调函数和方法是编程中强大而灵活的工具,通过允许函数或方法作为参数传递并在特定事件发生时执行,可以实现高度可扩展和模块化的代码结构。理解和善用回调机制,可以显著提升代码的灵活性和可维护性。
当然,让我们结合你提供的代码,深入探讨回调函数(Callback Function)或回调方法(Callback Method)的概念及其在该代码中的应用。
1. 回调函数/方法的基本概念回顾
回调函数是一种将函数(或方法)作为参数传递给另一个函数(或对象),并在特定事件或条件满足时执行该函数的编程技术。回调机制广泛应用于事件驱动编程、异步操作、框架扩展等场景,以实现灵活和可扩展的代码结构。
2. 你提供的代码概述
你提供的代码定义了一个名为 BaseCallback
的抽象基类(Abstract Base Class),继承自 ABC
(来自 Python 的 abc
模块)。该类包含多个方法,每个方法对应一个特定的事件,例如节点开始、节点结束、用户输入等。这些方法在事件发生时被调用,以处理相应的逻辑。
from abc import ABC
from bisheng.workflow.callback.event import NodeStartData, NodeEndData, OutputMsgChooseData, OutputMsgInputData, \
UserInputData, GuideWordData, GuideQuestionData, \
OutputMsgData, StreamMsgData, StreamMsgOverData
class BaseCallback(ABC):
def __init__(self, *args, **kwargs):
pass
def on_node_start(self, data: NodeStartData):
""" node start event """
print(f"node start: {data}")
def on_node_end(self, data: NodeEndData):
""" node end event """
print(f"node end: {data}")
def on_user_input(self, data: UserInputData):
""" user input event """
print(f"user input: {data}")
def on_guide_word(self, data: GuideWordData):
""" guide word event """
print(f"guide word: {data}")
def on_guide_question(self, data: GuideQuestionData):
""" guide question event """
print(f"guide question: {data}")
def on_stream_msg(self, data: StreamMsgData):
print(f"stream msg: {data}")
def on_stream_over(self, data: StreamMsgOverData):
print(f"stream over: {data}")
def on_output_msg(self, data: OutputMsgData):
print(f"output msg: {data}")
def on_output_choose(self, data: OutputMsgChooseData):
print(f"output choose: {data}")
def on_output_input(self, data: OutputMsgInputData):
print(f"output input: {data}")
3. 回调机制在此代码中的应用
3.1. BaseCallback 作为回调接口
BaseCallback
类充当了一个回调接口,定义了一系列的回调方法,每个方法对应一个特定的事件。当这些事件在工作流中发生时,相应的方法会被调用,以处理事件相关的逻辑。
- 抽象基类(ABC): 通过继承
ABC
,BaseCallback
类被定义为一个抽象基类。这意味着它旨在被子类化,子类需要实现或覆盖其中的方法以提供具体的行为。 - 回调方法: 每个
on_*
方法都是一个回调方法,用于响应特定的事件。例如,当节点开始时,on_node_start
方法会被调用,传递一个NodeStartData
对象作为参数。
3.2. 数据传递
每个回调方法都接受一个数据对象作为参数,如 NodeStartData
、UserInputData
等。这些数据类(通常是数据传输对象,DTOs)封装了事件发生时需要传递的信息,供回调方法使用。
4. 如何使用 BaseCallback 实现回调
为了利用 BaseCallback
的回调机制,你需要执行以下步骤:
4.1. 创建 BaseCallback 的子类
首先,创建一个继承自 BaseCallback
的子类,并根据需要覆盖回调方法,以实现自定义的事件处理逻辑。
class CustomCallback(BaseCallback):
def on_node_start(self, data: NodeStartData):
# 调用父类方法(可选)
super().on_node_start(data)
# 添加自定义逻辑
print(f"Custom handling for node start: {data}")
def on_user_input(self, data: UserInputData):
# 覆盖父类方法,实现自定义行为
print(f"Received user input: {data.input}")
4.2. 在工作流中注册回调
假设你的工作流框架允许注册回调对象,当特定事件发生时,会调用相应的回调方法。你需要将 CustomCallback
的实例传递给工作流框架。
def main():
# 创建回调对象
callback = CustomCallback()
# 假设 workflow 是你的工作流实例
workflow = Workflow(callback=callback)
# 启动工作流
workflow.run()
4.3. 工作流触发回调
当工作流中的某个事件发生时,例如节点开始,工作流会调用回调对象的相应方法:
class Workflow:
def __init__(self, callback: BaseCallback):
self.callback = callback
def run(self):
# 触发节点开始事件
node_start_data = NodeStartData(node_id=1, node_name="StartNode")
self.callback.on_node_start(node_start_data)
# 模拟其他事件
user_input_data = UserInputData(input="User input example")
self.callback.on_user_input(user_input_data)
# 触发节点结束事件
node_end_data = NodeEndData(node_id=1, node_name="StartNode")
self.callback.on_node_end(node_end_data)
运行 main()
函数时的输出:
node start: NodeStartData(node_id=1, node_name='StartNode')
Custom handling for node start: NodeStartData(node_id=1, node_name='StartNode')
Received user input: User input example
node end: NodeEndData(node_id=1, node_name='StartNode')
5. 详细解释
5.1. BaseCallback 类的角色
BaseCallback
类定义了一系列回调方法,这些方法在事件发生时被调用。它们的默认实现通常是打印日志或执行简单的操作,但通过子类化,可以扩展或替换这些行为以实现更复杂的逻辑。
5.2. 回调的流程
- 定义回调接口:
BaseCallback
作为回调接口,定义了处理各种事件的方法。 - 实现回调逻辑: 通过创建
BaseCallback
的子类并覆盖所需的方法,实现自定义的事件处理逻辑。 - 注册回调对象: 将回调对象传递给工作流或事件源,使其在事件发生时能够调用相应的回调方法。
- 事件触发和回调执行: 当事件发生时,工作流或事件源调用回调对象的相应方法,传递必要的数据,从而执行自定义逻辑。
5.3. 优点
- 解耦: 回调机制将事件发生的逻辑与事件处理的逻辑分离,降低了代码的耦合度,提高了模块的独立性。
- 可扩展性: 通过简单地继承和覆盖回调方法,可以轻松添加或修改事件处理逻辑,而无需修改核心框架代码。
- 灵活性: 允许在不同的上下文中使用不同的回调实现,以适应不同的需求和场景。
6. 实际应用中的回调示例
让我们通过一个更具体的示例来说明回调的工作原理。
6.1. 定义数据类
假设 bisheng.workflow.callback.event
模块中的数据类定义如下:
# bisheng/workflow/callback/event.py
from dataclasses import dataclass
@dataclass
class NodeStartData:
node_id: int
node_name: str
@dataclass
class NodeEndData:
node_id: int
node_name: str
@dataclass
class UserInputData:
input: str
# 其他数据类类似定义
6.2. 创建自定义回调类
class LoggingCallback(BaseCallback):
def on_node_start(self, data: NodeStartData):
# 记录节点开始
print(f"[LOG] Node {data.node_id} ('{data.node_name}') has started.")
def on_node_end(self, data: NodeEndData):
# 记录节点结束
print(f"[LOG] Node {data.node_id} ('{data.node_name}') has ended.")
def on_user_input(self, data: UserInputData):
# 处理用户输入
print(f"[USER INPUT] {data.input}")
6.3. 注册和触发回调
def main():
# 创建自定义回调实例
callback = LoggingCallback()
# 初始化工作流并注册回调
workflow = Workflow(callback=callback)
# 运行工作流,触发事件
workflow.run()
if __name__ == "__main__":
main()
输出:
[LOG] Node 1 ('StartNode') has started.
[USER INPUT] User input example
[LOG] Node 1 ('StartNode') has ended.
7. 总结
在你提供的代码中,BaseCallback
类作为回调接口,定义了一系列事件处理方法。这些方法在事件发生时被调用,允许开发者通过继承并覆盖这些方法,实现自定义的事件处理逻辑。通过回调机制,你可以将事件的触发与事件的处理解耦,使得代码更加模块化、灵活和可维护。
关键点回顾:
- 抽象基类:
BaseCallback
作为抽象基类,定义了回调方法的接口。 - 数据传递: 每个回调方法接收特定的数据对象,封装了事件相关的信息。
- 子类化: 通过创建
BaseCallback
的子类,并覆盖所需的方法,实现自定义的事件处理逻辑。 - 注册与触发: 将回调对象注册到工作流或事件源中,事件发生时自动调用相应的回调方法。
通过理解和应用回调机制,你可以设计出更加灵活和可扩展的系统,适应复杂多变的业务需求。
当然,下面我将为你生成一个简单的 Python 工程,以演示回调(Callback)机制的工作原理。这个示例将包括以下部分:
- 项目结构:展示项目的目录和文件布局。
- 数据类:定义事件数据类。
- 回调基类:定义一个基于
ABC
的回调基类。 - 自定义回调类:继承回调基类并实现自定义逻辑。
- 工作流类:模拟一个工作流,触发事件并调用回调方法。
- 主脚本:运行整个示例。
1. 项目结构
假设项目名为 callback_demo
,目录结构如下:
callback_demo/
├── callbacks/
│ ├── __init__.py
│ ├── base_callback.py
│ └── custom_callback.py
├── workflow/
│ ├── __init__.py
│ └── workflow.py
├── events/
│ ├── __init__.py
│ └── event_data.py
├── main.py
└── README.md
2. 创建项目目录和文件
首先,创建上述目录和文件。你可以使用以下命令在终端中完成:
mkdir callback_demo
cd callback_demo
mkdir callbacks workflow events
touch callbacks/__init__.py callbacks/base_callback.py callbacks/custom_callback.py
touch workflow/__init__.py workflow/workflow.py
touch events/__init__.py events/event_data.py
touch main.py README.md
3. 定义事件数据类
在 events/event_data.py
中定义各种事件的数据类。这些类使用 dataclasses
模块,便于数据的存储和传递。
# events/event_data.py
from dataclasses import dataclass
@dataclass
class NodeStartData:
node_id: int
node_name: str
@dataclass
class NodeEndData:
node_id: int
node_name: str
@dataclass
class UserInputData:
input: str
@dataclass
class GuideWordData:
word: str
@dataclass
class GuideQuestionData:
question: str
@dataclass
class StreamMsgData:
message: str
@dataclass
class StreamMsgOverData:
status: str
@dataclass
class OutputMsgData:
message: str
@dataclass
class OutputMsgChooseData:
choices: list
@dataclass
class OutputMsgInputData:
input: str
4. 定义回调基类
在 callbacks/base_callback.py
中定义一个抽象的回调基类 BaseCallback
,包含多个回调方法,每个方法对应一个特定的事件。
# callbacks/base_callback.py
from abc import ABC
from events.event_data import (
NodeStartData, NodeEndData, OutputMsgChooseData, OutputMsgInputData,
UserInputData, GuideWordData, GuideQuestionData,
OutputMsgData, StreamMsgData, StreamMsgOverData
)
class BaseCallback(ABC):
def __init__(self, *args, **kwargs):
pass
def on_node_start(self, data: NodeStartData):
""" node start event """
print(f"[BaseCallback] Node start: {data}")
def on_node_end(self, data: NodeEndData):
""" node end event """
print(f"[BaseCallback] Node end: {data}")
def on_user_input(self, data: UserInputData):
""" user input event """
print(f"[BaseCallback] User input: {data}")
def on_guide_word(self, data: GuideWordData):
""" guide word event """
print(f"[BaseCallback] Guide word: {data}")
def on_guide_question(self, data: GuideQuestionData):
""" guide question event """
print(f"[BaseCallback] Guide question: {data}")
def on_stream_msg(self, data: StreamMsgData):
print(f"[BaseCallback] Stream msg: {data}")
def on_stream_over(self, data: StreamMsgOverData):
print(f"[BaseCallback] Stream over: {data}")
def on_output_msg(self, data: OutputMsgData):
print(f"[BaseCallback] Output msg: {data}")
def on_output_choose(self, data: OutputMsgChooseData):
print(f"[BaseCallback] Output choose: {data}")
def on_output_input(self, data: OutputMsgInputData):
print(f"[BaseCallback] Output input: {data}")
5. 实现自定义回调类
在 callbacks/custom_callback.py
中创建一个继承自 BaseCallback
的自定义回调类 CustomCallback
,覆盖部分方法以实现自定义逻辑。
# callbacks/custom_callback.py
from callbacks.base_callback import BaseCallback
from events.event_data import (
NodeStartData, NodeEndData, OutputMsgChooseData, OutputMsgInputData,
UserInputData, GuideWordData, GuideQuestionData,
OutputMsgData, StreamMsgData, StreamMsgOverData
)
class CustomCallback(BaseCallback):
def on_node_start(self, data: NodeStartData):
print(f"[CustomCallback] Starting node {data.node_id}: {data.node_name}")
def on_node_end(self, data: NodeEndData):
print(f"[CustomCallback] Ending node {data.node_id}: {data.node_name}")
def on_user_input(self, data: UserInputData):
print(f"[CustomCallback] Received user input: {data.input}")
# 你可以根据需要覆盖更多的回调方法
6. 创建工作流类
在 workflow/workflow.py
中定义一个 Workflow
类,负责触发事件并调用回调方法。
# workflow/workflow.py
from callbacks.base_callback import BaseCallback
from events.event_data import (
NodeStartData, NodeEndData, OutputMsgChooseData, OutputMsgInputData,
UserInputData, GuideWordData, GuideQuestionData,
OutputMsgData, StreamMsgData, StreamMsgOverData
)
class Workflow:
def __init__(self, callback: BaseCallback):
self.callback = callback
def run(self):
# 模拟节点开始事件
node_start = NodeStartData(node_id=1, node_name="Initialization")
self.callback.on_node_start(node_start)
# 模拟用户输入事件
user_input = UserInputData(input="User entered some data.")
self.callback.on_user_input(user_input)
# 模拟输出消息事件
output_msg = OutputMsgData(message="Processing complete.")
self.callback.on_output_msg(output_msg)
# 模拟节点结束事件
node_end = NodeEndData(node_id=1, node_name="Initialization")
self.callback.on_node_end(node_end)
# 你可以在这里添加更多的事件触发
7. 编写主脚本
在 main.py
中创建回调对象,初始化工作流并运行它。
# main.py
from callbacks.custom_callback import CustomCallback
from workflow.workflow import Workflow
def main():
# 创建自定义回调实例
callback = CustomCallback()
# 初始化工作流并注册回调
workflow = Workflow(callback=callback)
# 运行工作流,触发事件
workflow.run()
if __name__ == "__main__":
main()
8. 运行示例
确保你当前所在的目录是 callback_demo
,然后运行主脚本:
python main.py
预期输出:
[CustomCallback] Starting node 1: Initialization
[CustomCallback] Received user input: User entered some data.
[BaseCallback] Output msg: OutputMsgData(message='Processing complete.')
[CustomCallback] Ending node 1: Initialization
9. 详细解释
让我们逐步解析这个示例,理解回调机制是如何运作的。
9.1. 事件数据类
在 events/event_data.py
中,我们定义了多个数据类,每个类对应一个特定的事件。例如,NodeStartData
包含节点的 ID 和名称,UserInputData
包含用户输入的数据。这些数据类用于在事件触发时传递相关信息。
9.2. 回调基类
callbacks/base_callback.py
中的 BaseCallback
类是一个抽象基类,定义了一系列回调方法,如 on_node_start
、on_user_input
等。每个方法对应一个事件,默认实现是打印事件信息。
9.3. 自定义回调类
在 callbacks/custom_callback.py
中,我们创建了 CustomCallback
类,继承自 BaseCallback
,并覆盖了部分回调方法以实现自定义逻辑。例如,on_node_start
方法被覆盖为打印更详细的启动信息。
9.4. 工作流类
workflow/workflow.py
中的 Workflow
类负责模拟工作流的运行过程。它接收一个 BaseCallback
对象作为参数,并在工作流运行过程中触发不同的事件,调用相应的回调方法。
9.5. 主脚本
main.py
是程序的入口点。它创建一个 CustomCallback
实例,初始化 Workflow
类并传递回调对象,然后运行工作流。运行过程中,工作流会触发事件并调用回调方法。
9.6. 回调流程总结
- 定义事件:使用数据类定义各种事件的数据结构。
- 定义回调接口:通过
BaseCallback
定义回调方法的接口。 - 实现回调逻辑:通过继承
BaseCallback
实现具体的回调逻辑。 - 注册回调:将回调对象传递给工作流或事件源。
- 触发事件:工作流在运行过程中触发事件,调用相应的回调方法。
- 处理事件:回调方法执行自定义的事件处理逻辑。
10. 扩展与改进
这个示例展示了回调机制的基本用法。根据实际需求,你可以进一步扩展这个项目:
- 添加更多事件:定义更多的事件数据类和对应的回调方法。
- 多重回调:支持注册多个回调对象,所有回调对象在事件触发时都被调用。
- 异步回调:结合
asyncio
实现异步事件处理。 - 错误处理:在回调方法中添加错误处理逻辑,确保回调执行不会中断工作流。
11. 完整代码汇总
为了方便你快速查看和测试,以下是所有文件的完整代码。
events/event_data.py
from dataclasses import dataclass
@dataclass
class NodeStartData:
node_id: int
node_name: str
@dataclass
class NodeEndData:
node_id: int
node_name: str
@dataclass
class UserInputData:
input: str
@dataclass
class GuideWordData:
word: str
@dataclass
class GuideQuestionData:
question: str
@dataclass
class StreamMsgData:
message: str
@dataclass
class StreamMsgOverData:
status: str
@dataclass
class OutputMsgData:
message: str
@dataclass
class OutputMsgChooseData:
choices: list
@dataclass
class OutputMsgInputData:
input: str
callbacks/base_callback.py
from abc import ABC
from events.event_data import (
NodeStartData, NodeEndData, OutputMsgChooseData, OutputMsgInputData,
UserInputData, GuideWordData, GuideQuestionData,
OutputMsgData, StreamMsgData, StreamMsgOverData
)
class BaseCallback(ABC):
def __init__(self, *args, **kwargs):
pass
def on_node_start(self, data: NodeStartData):
""" node start event """
print(f"[BaseCallback] Node start: {data}")
def on_node_end(self, data: NodeEndData):
""" node end event """
print(f"[BaseCallback] Node end: {data}")
def on_user_input(self, data: UserInputData):
""" user input event """
print(f"[BaseCallback] User input: {data}")
def on_guide_word(self, data: GuideWordData):
""" guide word event """
print(f"[BaseCallback] Guide word: {data}")
def on_guide_question(self, data: GuideQuestionData):
""" guide question event """
print(f"[BaseCallback] Guide question: {data}")
def on_stream_msg(self, data: StreamMsgData):
print(f"[BaseCallback] Stream msg: {data}")
def on_stream_over(self, data: StreamMsgOverData):
print(f"[BaseCallback] Stream over: {data}")
def on_output_msg(self, data: OutputMsgData):
print(f"[BaseCallback] Output msg: {data}")
def on_output_choose(self, data: OutputMsgChooseData):
print(f"[BaseCallback] Output choose: {data}")
def on_output_input(self, data: OutputMsgInputData):
print(f"[BaseCallback] Output input: {data}")
callbacks/custom_callback.py
from callbacks.base_callback import BaseCallback
from events.event_data import (
NodeStartData, NodeEndData, OutputMsgChooseData, OutputMsgInputData,
UserInputData, GuideWordData, GuideQuestionData,
OutputMsgData, StreamMsgData, StreamMsgOverData
)
class CustomCallback(BaseCallback):
def on_node_start(self, data: NodeStartData):
print(f"[CustomCallback] Starting node {data.node_id}: {data.node_name}")
def on_node_end(self, data: NodeEndData):
print(f"[CustomCallback] Ending node {data.node_id}: {data.node_name}")
def on_user_input(self, data: UserInputData):
print(f"[CustomCallback] Received user input: {data.input}")
# 你可以根据需要覆盖更多的回调方法
workflow/workflow.py
from callbacks.base_callback import BaseCallback
from events.event_data import (
NodeStartData, NodeEndData, OutputMsgChooseData, OutputMsgInputData,
UserInputData, GuideWordData, GuideQuestionData,
OutputMsgData, StreamMsgData, StreamMsgOverData
)
class Workflow:
def __init__(self, callback: BaseCallback):
self.callback = callback
def run(self):
# 模拟节点开始事件
node_start = NodeStartData(node_id=1, node_name="Initialization")
self.callback.on_node_start(node_start)
# 模拟用户输入事件
user_input = UserInputData(input="User entered some data.")
self.callback.on_user_input(user_input)
# 模拟输出消息事件
output_msg = OutputMsgData(message="Processing complete.")
self.callback.on_output_msg(output_msg)
# 模拟节点结束事件
node_end = NodeEndData(node_id=1, node_name="Initialization")
self.callback.on_node_end(node_end)
# 你可以在这里添加更多的事件触发
main.py
from callbacks.custom_callback import CustomCallback
from workflow.workflow import Workflow
def main():
# 创建自定义回调实例
callback = CustomCallback()
# 初始化工作流并注册回调
workflow = Workflow(callback=callback)
# 运行工作流,触发事件
workflow.run()
if __name__ == "__main__":
main()
12. 结论
通过这个简单的 Python 工程示例,你可以清晰地理解回调机制的工作原理。回调机制允许你在特定事件发生时执行预定义的逻辑,从而实现代码的灵活性和可扩展性。你可以根据实际需求,进一步扩展和优化这个示例,以适应更复杂的应用场景。
如果你有任何问题或需要进一步的帮助,请随时告诉我!