萬盛學電腦網

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

Python apply() 以元組/列表解包呼叫函式 Python apply() 以元組/列表解包呼叫函式

apply(func, args, kwargs) 是 Python 2 時代將序列解包為位置/關鍵字參數呼叫函式的標準方式。Python 3 已移除,改用 *args/**kwargs 解包語法。本文展示兩種語法對照與現代最佳實踐。

Python 2 apply 範例 (已棄用)


def my_func(a, b):
    print(a, b)

atuple = (30, 10)
alist = ['Hello', 'World!']

apply(my_func, atuple)   # 30 10
apply(my_func, alist)    # Hello World!

Python 3 現代寫法:解包運算子


def my_func(a, b):
    print(a, b)

atuple = (30, 10)
alist = ['Hello', 'World!']
adict = {'a': 100, 'b': 200}

my_func(*atuple)   # 30 10
my_func(*alist)    # Hello World!
my_func(**adict)   # 100 200

實務應用場景

  • 裝飾器透傳:def wrapper(*args, **kwargs): return func(*args, **kwargs)
  • 動態呼叫:getattr(obj, method_name)(*args, **kwargs)
  • 參數預設值合併:final_kwargs = {**defaults, **user_kwargs}
  • 函式簽名檢查:inspect.signature(func).bind(*args, **kwargs) 驗證參數相容性。

效能對比

apply 為函式呼叫,有函式開銷;*args 為語法糖,直接編譯為 CALL_FUNCTION_EX 位元碼,效能略優。現代碼庫請全面改用解包語法。

copyright © 萬盛學電腦網 all rights reserved