萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 回呼函數完整解析:同步、回呼與非同步調用模式

軟體模組間的調用模式主要分三類:同步調用 (阻塞等待)、回呼 (雙向調用)、非同步調用 (事件/訊息驅動)。回呼是實現非同步通知的基礎。本文詳細說明 Python 回呼機制、常見模式與實務技巧。

基本回呼範例

# caller.py
import callee

def callback():
    print("in callback")

def main():
    callee.test_call(callback)
    print("in caller")

if __name__ == '__main__':
    main()

# callee.py
def test_call(callback_func):
    print("in callee test_call")
    callback_func()  # 執行呼叫端傳入的函數

輸出:

in callee test_call
in callback
in caller

回呼分類與用法

1. 簡單函數回呼

def process(data, on_complete):
    result = do_work(data)
    on_complete(result)

def handle_result(res):
    print(f"Result: {res}")

process("input", handle_result)

2. 物件方法回呼 (需綁定 self)

class Handler:
    def on_done(self, result):
        print(f"Handler got: {result}")

h = Handler()
process("data", h.on_done)  # 傳入綁定方法

3. Lambda/匿名函數回呼

process("data", lambda r: print(f"Lambda got: {r}"))

4. 帶參數回呼 (使用 functools.partial)

from functools import partial

def callback_with_context(ctx, result):
    print(f"[{ctx}] Result: {result}")

process("data", partial(callback_with_context, "Job-123"))

非同步回呼模式 (事件循環)

import asyncio

async def fetch_data(url, callback):
    # 模擬非同步 IO
    await asyncio.sleep(1)
    data = f"Data from {url}"
    callback(data)

def on_data(data):
    print(f"Received: {data}")

async def main():
    await fetch_data("https://api.example.com", on_data)

asyncio.run(main())

實務設計原則

  • 錯誤傳遞:回呼簽名建議包含 (error, result) 或使用 try/except 在回呼內處理。
  • 避免回呼地獄:多層巢狀回呼改用 async/await、concurrent.futures 或 Promise 風格。
  • 型別提示:Callable[[ResultType], None] 提升可讀性與靜態檢查。
  • 弱引用:長生命週期物件持有回呼時,用 weakref 避免循環引用導致記憶體洩漏。

標準庫中的回呼應用

  • atexit.register(func):程式退出時回呼。
  • signal.signal(signum, handler):訊號處理。
  • threading.Timer(interval, func):定時回呼。
  • asyncio.add_reader(fd, callback):IO 多工回呼。

回呼是 Python 事件驅動程式設計的基石,善用現代非同步語法可大幅降低複雜度。

copyright © 萬盛學電腦網 all rights reserved