返回专栏
· 13 分钟阅读

Python 参数解包与函数调用


一、什么是参数解包?

参数解包(Argument Unpacking)是指在函数调用时,使用特定语法将一个可迭代对象或映射对象中的数据展开,作为独立的函数实参传递。

Python 主要使用两种解包方式:

  • *:将可迭代对象展开为位置参数。
  • **:将映射对象展开为关键字参数。

例如:

def add(a, b, c):
    return a + b + c


numbers = [10, 20, 30]

print(add(*numbers))

输出:

60

这里的 *numbers 将列表中的三个元素展开,相当于:

add(10, 20, 30)

再看一个字典解包示例:

def introduce(name, age, city):
    print(name, age, city)


user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

introduce(**user)

输出:

Alice 25 Tokyo

相当于:

introduce(
    name="Alice",
    age=25,
    city="Tokyo"
)

参数解包的核心价值是:将数据结构中的内容转换为函数调用所需要的位置参数或关键字参数。

二、使用 * 解包位置参数

单星号 * 可以将列表、元组或其他可迭代对象展开为多个位置参数。

1. 解包列表

def calculate(a, b, c):
    return a + b + c


numbers = [10, 20, 30]

result = calculate(*numbers)

print(result)

输出:

60

等价于:

calculate(10, 20, 30)

列表中的每个元素按照迭代顺序,依次匹配函数形参。

2. 解包元组

def introduce(name, age, city):
    print(f"姓名:{name}")
    print(f"年龄:{age}")
    print(f"城市:{city}")


user = ("Alice", 25, "Tokyo")

introduce(*user)

输出:

姓名:Alice
年龄:25
城市:Tokyo

元组和列表一样,都可以使用单星号解包。

3. 解包字符串

字符串也是可迭代对象,因此也可以使用 * 解包。

def show(a, b, c):
    print(a, b, c)


show(*"ABC")

输出:

A B C

字符串会按照字符迭代,每个字符成为一个位置参数。

但在实际开发中,除非确实需要逐字符传参,否则通常不建议这样使用,因为它容易让代码意图变得不清晰。

4. 解包 range 对象

def add(a, b, c, d):
    return a + b + c + d


numbers = range(1, 5)

print(add(*numbers))

输出:

10

range(1, 5) 产生的元素依次展开为四个位置参数。

5. 解包对象必须满足参数数量要求

def add(a, b, c):
    return a + b + c


numbers = [10, 20]

add(*numbers)

运行时会产生 TypeError,因为函数需要三个位置参数,而解包只提供了两个。

如果参数数量超过函数能够接收的范围,同样会产生参数绑定错误。

numbers = [10, 20, 30, 40]

add(*numbers)

因此,使用 * 解包时,需要保证展开后的参数数量和函数签名相匹配。

三、使用 ** 解包关键字参数

双星号 ** 用于将字典等映射对象展开为关键字参数。

1. 解包字典

def create_user(name, age, city):
    print(name, age, city)


user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

create_user(**user)

输出:

Alice 25 Tokyo

这里:

  • name 对应函数形参 name。
  • age 对应函数形参 age。
  • city 对应函数形参 city。

字典的键决定关键字参数名称,字典的值作为对应参数的实参。

2. 字典键必须符合关键字参数要求

def show(name, age):
    print(name, age)


user = {
    "name": "Alice",
    "age": 25
}

show(**user)

正常执行。

如果字典中存在不符合函数参数名称要求的键,并且没有对应的 **kwargs 接收,就可能产生 TypeError。

def show(name, age):
    print(name, age)


user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

show(**user)

错误原因是函数没有定义 city 参数,也没有可变关键字参数接收它。

另外,使用 ** 解包时,映射中的键必须是字符串,并且需要符合关键字传参的要求。

3. 字典解包与默认参数

如果函数形参具有默认值,字典可以只提供部分参数。

def connect(host, port=8080, timeout=10):
    print(host, port, timeout)


config = {
    "host": "localhost",
    "timeout": 30
}

connect(**config)

输出:

localhost 8080 30

其中:

  • host 从字典中获取。
  • port 没有提供,使用默认值 8080。
  • timeout 从字典中获取。

4. 字典解包支持多个映射对象

在函数调用中,可以连续使用多个 **。

def create_user(name, age, city):
    print(name, age, city)


basic = {
    "name": "Alice",
    "age": 25
}

location = {
    "city": "Tokyo"
}

create_user(**basic, **location)

输出:

Alice 25 Tokyo

多个映射对象中的参数会一起参与函数参数绑定。

如果多个字典提供了同一个关键字名称,就会产生重复绑定错误。

basic = {
    "name": "Alice"
}

other = {
    "name": "Bob"
}

create_user(**basic, **other)

这会产生 TypeError,因为 name 被重复传递。

如果希望合并字典并让后面的值覆盖前面的值,可以先合并字典,再进行解包:

basic = {
    "name": "Alice",
    "age": 25
}

other = {
    "name": "Bob",
    "city": "Tokyo"
}

config = {**basic, **other}

create_user(**config)

输出:

Bob 25 Tokyo

这里字典合并发生在函数调用之前,后面的 name 覆盖了前面的 name。

四、同时使用 * 与 ** 解包

Python 允许在同一次函数调用中同时使用位置参数解包和关键字参数解包。

1. 基本组合方式

def create_order(product, quantity, price, currency="CNY"):
    print(product, quantity, price, currency)


args = ("Laptop", 2)

kwargs = {
    "price": 5999,
    "currency": "CNY"
}

create_order(*args, **kwargs)

输出:

Laptop 2 5999 CNY

其中:

  • *args 展开为位置参数。
  • **kwargs 展开为关键字参数。

等价于:

create_order(
    "Laptop",
    2,
    price=5999,
    currency="CNY"
)

2. 混合普通参数与解包参数

def introduce(name, age, city, job):
    print(name, age, city, job)


basic = ["Alice", 25]

extra = {
    "city": "Tokyo",
    "job": "Engineer"
}

introduce(*basic, **extra)

输出:

Alice 25 Tokyo Engineer

函数调用可以将固定参数、位置解包和关键字解包组合起来。

3. 位置参数和关键字参数不能重复绑定

def introduce(name, age):
    print(name, age)


data = {
    "name": "Bob",
    "age": 25
}

introduce("Alice", **data)

这会产生 TypeError。

原因是:

  • "Alice" 已经通过位置参数绑定给 name。
  • **data 又提供了 name="Bob"。
  • 同一个形参被重复赋值。

正确写法:

introduce("Alice", age=25)

4. 参数解包的完整过程

flowchart TD
    A["准备函数调用数据"] --> B{"是否需要解包"}
    B -->|否| C["直接传递实参"]
    B -->|是| D{"解包方式"}
    D -->|单星号| E["展开可迭代对象"]
    D -->|双星号| F["展开映射对象"]
    E --> G["生成位置参数"]
    F --> H["生成关键字参数"]
    C --> I["执行参数绑定"]
    G --> I
    H --> I
    I --> J{"绑定是否成功"}
    J -->|是| K["执行函数体"]
    J -->|否| L["抛出 TypeError"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

五、函数定义中的参数收集与函数调用中的参数解包

这是 Python 函数参数机制中非常容易混淆的知识点。

*args 和 **kwargs 既可以出现在函数定义中,也可以出现在函数调用中,但它们承担的任务不同。

1. 函数定义中的参数收集

def show(*args, **kwargs):
    print(args)
    print(kwargs)


show(10, 20, name="Alice", age=25)

输出:

(10, 20)
{'name': 'Alice', 'age': 25}

这里:

  • 函数定义中的 *args 收集额外的位置参数。
  • 函数定义中的 **kwargs 收集额外的关键字参数。

2. 函数调用中的参数解包

def show(a, b, name, age):
    print(a, b, name, age)


args = (10, 20)

kwargs = {
    "name": "Alice",
    "age": 25
}

show(*args, **kwargs)

这里:

  • 调用表达式中的 *args 展开元组。
  • 调用表达式中的 **kwargs 展开字典。

3. 收集与解包的对比

使用位置 语法 作用 结果
函数定义 *args 收集位置参数 元组
函数定义 **kwargs 收集关键字参数 字典
函数调用 *values 展开可迭代对象 位置实参
函数调用 **config 展开映射对象 关键字实参

可以简单记忆:

定义函数时,星号负责收集;调用函数时,星号负责展开。

六、Python 的多层解包与嵌套结构

除了简单列表、元组和字典,Python 还支持将复杂数据结构组合起来进行参数解包。

1. 解包嵌套列表

def create_point(x, y, z):
    print(f"坐标:{x}, {y}, {z}")


point = [10, [20, 30]]

create_point(point[0], *point[1])

输出:

坐标:10, 20, 30

这里将外层列表的第一个元素作为普通位置参数,再将内部列表展开。

2. 使用字典合并多个配置

def connect(host, port, timeout, retry):
    print(host, port, timeout, retry)


default_config = {
    "host": "localhost",
    "port": 8080,
    "timeout": 10,
    "retry": 3
}

custom_config = {
    "timeout": 30,
    "retry": 5
}

config = {
    **default_config,
    **custom_config
}

connect(**config)

输出:

localhost 8080 30 5

这种方式常用于:

  • 默认配置与用户配置合并。
  • 环境配置覆盖。
  • API 请求参数组合。
  • 多层配置管理。

需要注意,{**a, **b} 是创建新的字典,不会递归合并内部嵌套字典。

例如:

default = {
    "database": {
        "host": "localhost",
        "port": 3306
    }
}

custom = {
    "database": {
        "host": "db.example.com"
    }
}

config = {
    **default,
    **custom
}

print(config)

结果:

{
    'database': {
        'host': 'db.example.com'
    }
}

整个 database 值被替换,而不是只覆盖其中的 host。

3. 使用字典解包构造新字典

user = {
    "name": "Alice",
    "age": 25
}

extra = {
    "city": "Tokyo",
    "job": "Engineer"
}

profile = {
    **user,
    **extra,
    "active": True
}

print(profile)

输出:

{
    'name': 'Alice',
    'age': 25,
    'city': 'Tokyo',
    'job': 'Engineer',
    'active': True
}

这种写法在数据转换、配置组合和构造请求参数时非常常见。

七、解包与迭代解包的区别

Python 中还有一种容易与函数参数解包混淆的语法:序列解包。

例如:

a, b, c = [10, 20, 30]

print(a, b, c)

这也是解包,但它不是函数调用中的参数解包。

1. 序列解包

序列解包用于将可迭代对象中的元素分配给多个变量。

numbers = [10, 20, 30]

a, b, c = numbers

2. 扩展序列解包

使用单星号可以接收剩余元素。

numbers = [10, 20, 30, 40, 50]

first, *middle, last = numbers

print(first)
print(middle)
print(last)

输出:

10
[20, 30, 40]
50

这里的 *middle 收集剩余元素,结果是列表。

3. 三种解包方式对比

解包形式 主要用途 结果
函数调用 * 展开位置实参 多个位置参数
函数调用 ** 展开关键字实参 多个关键字参数
赋值语句 * 收集剩余元素 列表

例如: