萬盛學電腦網

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

Python 函數參數傳遞機制與可變長參數深度解析

核心概念:調用機制是「傳對象引用」

Python 既不是「傳值」也不是「傳引用」,而是 **Call by Object Reference(傳對象引用)**:

  • 參數傳遞的是對象的**引用(指針)副本**。
  • 函數內部對**可變對象**(列表、字典、集合、自定義對象)的**修改**會影響外部原對象。
  • 函數內部對**不可變對象**(整數、字符串、元組、frozenset)**重新賦值**只改變局部引用指向,不影響外部。

參數類型完整分類


def func(
    a,                    # 1. 位置參數
    b=10,                 # 2. 默認參數(必須在非默認參數後)
    *args,                # 3. 可變位置參數 (tuple)
    c,                    # 4. 僅關鍵字參數 (Python 3+,* 後面的參數)
    d=20,                 # 5. 帶默認值的僅關鍵字參數
    **kwargs              # 6. 可變關鍵字參數 (dict)
):
    pass

各類參數深度解析

1. 默認參數:陷阱與最佳實踐


# ❌ 危險:默認值在定義時計算一次,所有調用共享同一可變對象
def bad_append(item, lst=[]):
    lst.append(item)
    return lst

print(bad_append(1))  # [1]
print(bad_append(2))  # [1, 2]  !!! 共享同一列表

# ✅ 正確:用 None 做哨兵,函數內創建新對象
def good_append(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst

print(good_append(1))  # [1]
print(good_append(2))  # [2]

2. 可變位置參數 *args


def demo_args(a, b, *args):
    print(f"a={a}, b={b}, args={args}")

demo_args(1, 2)           # a=1, b=2, args=()
demo_args(1, 2, 3, 4, 5)  # a=1, b=2, args=(3, 4, 5)

# 解包調用
values = [10, 20, 30, 40]
demo_args(*values)        # a=10, b=20, args=(30, 40)

3. 可變關鍵字參數 **kwargs


def demo_kwargs(a, b, **kwargs):
    print(f"a={a}, b={b}, kwargs={kwargs}")

demo_kwargs(1, 2)                    # a=1, b=2, kwargs={}
demo_kwargs(1, 2, x=10, y=20)        # a=1, b=2, kwargs={'x':10, 'y':20}

# 解包字典調用
params = {'x': 100, 'y': 200}
demo_kwargs(1, 2, **params)          # a=1, b=2, kwargs={'x':100, 'y':200}

4. 僅關鍵字參數


def greet(name, *, greeting="Hello", punctuation="!"):
    """greeting 和 punctuation 必須用關鍵字傳遞"""
    print(f"{greeting}, {name}{punctuation}")

greet("World")                    # Hello, World!
greet("World", greeting="Hi")     # Hi, World!
# greet("World", "Hi")            # TypeError: positional argument follows keyword-only

參數傳遞順序規則(調用時)

  1. 位置參數
  2. 關鍵字參數
  3. *args 解包
  4. **kwargs 解包

def f(a, b, c, d): print(a,b,c,d)

f(1, 2, 3, 4)
f(1, 2, c=3, d=4)
f(1, b=2, c=3, d=4)
f(a=1, b=2, c=3, d=4)
f(*[1,2], **{'c':3, 'd':4})
f(1, *[2], **{'c':3, 'd':4})
# f(1, **{'b':2}, 3)  # 錯誤:關鍵字解包後不能有位置參數

參數綁定機制圖解


def modify(x, y, z):
    x = 10           # 重新綁定局部變量 x(不可變對象,外部不變)
    y.append(99)     # 修改可變對象內容(外部可見)
    z = {'a': 1}     # 重新綁定局部變量 z(外部不變)

a = 5
b = [1, 2]
c = {'x': 10}
modify(a, b, c)
print(a)  # 5 (未變)
print(b)  # [1, 2, 99] (已變)
print(c)  # {'x': 10} (未變)

實戰模式:參數轉發與裝飾器


import functools
from typing import Callable, Any

def log_calls(func: Callable) -> Callable:
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"調用 {func.__name__}: args={args}, kwargs={kwargs}")
        result = func(*args, **kwargs)
        print(f"返回: {result}")
        return result
    return wrapper

@log_calls
def add(a: int, b: int, *, verbose: bool = False) -> int:
    return a + b

add(1, 2)
add(1, b=2, verbose=True)
add(*(3,), **{'b': 4})

類型註解與參數檢查 (Python 3.5+)


from typing import Optional, List, Dict, Any

def process_items(
    items: List[str],
    threshold: int = 10,
    *,
    filter_fn: Optional[Callable[[str], bool]] = None,
    metadata: Dict[str, Any] = None
) -> Dict[str, int]:
    metadata = metadata or {}
    filtered = [item for item in items if filter_fn is None or filter_fn(item)]
    return {'count': len(filtered), 'threshold': threshold, **metadata}

# 運行時類型檢查可用 pydantic / beartype / typeguard

常見錯誤與避坑

錯誤代碼問題修正
def f(a=[]):可變默認參數共享def f(a=None): a = a or []
f(*args, **kwargs, x=1)語法錯誤:*args 後不能有位置參數將 x 移至 *args 前或改為關鍵字參數
f(**dict1, **dict2) 有重複鍵TypeError: multiple values合併字典 {**dict1, **dict2} (後者覆蓋)
修改傳入的列表/字典副作用影響調用方文檔註明、或傳入副本 f(lst[:])、或用不可變類型

總結

Python 參數機制核心三點:

  1. 傳對象引用:可變對象修改可見,不可變對象重綁定不可見。
  2. 四類參數位置固定:位置 → 默認 → *args/關鍵字 → **kwargs。
  3. 解包調用:`*iterable`、`**mapping` 靈活構造調用。

熟練掌握默認參數陷阱、`*args/**kwargs` 轉發模式、僅關鍵字參數強制語義、裝飾器參數透傳,即可編寫靈活、健壯、可維護的 Python 函數接口。

copyright © 萬盛學電腦網 all rights reserved