在軟體模組互動中,調用方式主要有三類:同步調用(阻塞等待)、回調(雙向調用)與 異步調用(事件驅動)。回調模式下,被調用方在執行過程中會主動調用調用方提供的函數,形成雙向交互。回調常作為異步通知的基礎機制。
以下代碼展示兩個模組 call.py 與 called.py 的回調交互:
import called
def callback():
print("in callback")
def main():
called.test_call(callback)
print("in call.py")
if __name__ == "__main__":
main()
def test_call(p_call):
print("in called.py test_call()")
p_call() # 執行回調
in called.py test_call()
in callback
in call.py
def process_data(data, on_complete):
# 模擬耗時操作
result = data.upper()
on_complete(result) # 回調並傳遞結果
def handle_result(res):
print("處理完成:", res)
process_data("hello", handle_result)
# 輸出: 處理完成: HELLO
回調是 Python 實現事件驅動與異步編程的基石。掌握回調模式,能幫助你設計更靈活、可擴展的 API 與框架集成代碼。