返回专栏
· 13 分钟阅读

Python 位置参数与关键字参数


一、什么是位置参数与关键字参数

调用 Python 函数时,实参需要与函数定义中的形参建立对应关系。根据实参传递信息的方式,可以分为两种基本形式:

  • 位置参数(Positional Arguments):按照参数在函数定义中的位置进行匹配。
  • 关键字参数(Keyword Arguments):通过参数名称明确指定对应的形参。

1. 位置参数

位置参数根据传入顺序与函数形参进行匹配。

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


introduce("Alice", 25, "Tokyo")

输出:

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

参数绑定关系:

形参 实参 匹配方式
name "Alice" 第一个位置
age 25 第二个位置
city "Tokyo" 第三个位置

位置参数的特点:

  1. 参数顺序必须与函数定义中的形参顺序对应。
  2. 不需要显式写出参数名称。
  3. 调用简洁,适合参数含义明确、数量较少的场景。
  4. 参数顺序错误时,可能导致语义错误,甚至运行异常。

例如:

def calculate(a, b):
    return a - b


print(calculate(10, 3))  # 7
print(calculate(3, 10))  # -7

两个调用都合法,但结果不同,因为位置参数的顺序改变了。

2. 关键字参数

关键字参数通过形参名称指定实参,不依赖实参之间的排列顺序。

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


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

也可以调整关键字参数的顺序:

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

输出结果相同。

关键字参数的特点:

  1. 通过参数名称建立绑定关系。
  2. 不要求按照函数定义中的顺序传递。
  3. 可读性更强,适合参数较多或含义不明显的函数。
  4. 可以减少因参数顺序错误造成的误用。

3. 两种方式的对比

对比维度 位置参数 关键字参数
匹配依据 参数位置 参数名称
顺序要求 必须对应形参顺序 不要求固定顺序
可读性 取决于参数含义 通常更明确
调用形式 func(10, 20) func(a=10, b=20)
常见场景 简单、明确的参数 参数较多、配置型调用

二、位置参数与关键字参数的混合使用

Python 允许在同一次函数调用中混合使用位置参数和关键字参数,但必须遵循特定规则。

1. 位置参数必须放在关键字参数之前

正确示例:

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


create_user("Alice", age=25, city="Tokyo")

其中:

  • "Alice" 通过位置匹配 name。
  • age=25 通过名称匹配 age。
  • city="Tokyo" 通过名称匹配 city。

错误示例:

create_user(name="Alice", 25, city="Tokyo")

运行时会产生 SyntaxError,因为位置参数不能跟在关键字参数之后。

2. 位置参数与关键字参数不能重复赋值

同一个形参不能同时通过位置和关键字方式赋值。

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


introduce("Alice", name="Bob", age=25)

运行时会产生 TypeError:

TypeError: introduce() got multiple values for argument 'name'

原因是:

  • "Alice" 已经通过第一个位置参数绑定给 name。
  • name="Bob" 又试图给 name 赋值。
  • 同一个形参出现了重复绑定。

3. 混合调用的绑定过程

例如:

def order(product, quantity, price):
    print(product, quantity, price)


order("Laptop", price=5999, quantity=2)

参数绑定关系:

传入实参 绑定的形参
"Laptop" product
price=5999 price
quantity=2 quantity

混合调用时,Python 根据位置和名称分别完成匹配。

flowchart TD
    A["开始函数调用"] --> B["接收实参"]
    B --> C["处理位置参数"]
    C --> D["按顺序绑定形参"]
    D --> E["处理关键字参数"]
    E --> F["按名称绑定形参"]
    F --> G{"是否存在重复绑定"}
    G -->|是| H["抛出 TypeError"]
    G -->|否| I{"是否存在未赋值的必需参数"}
    I -->|是| J["抛出 TypeError"]
    I -->|否| K["完成参数绑定"]
    K --> L["执行函数体"]

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

注意:以上是便于理解的简化流程。实际调用还涉及参数种类限制、默认值处理、可变参数收集等规则。

三、位置参数与关键字参数的顺序规则

理解函数调用规则,关键是区分实参传递顺序与形参定义顺序。

1. 位置参数按照定义顺序绑定

def register(username, email, age):
    print(username, email, age)


register("Tom", "tom@example.com", 20)

对应关系:

第一个位置参数 → username
第二个位置参数 → email
第三个位置参数 → age

如果位置顺序发生变化,Python 不会根据数据内容自动判断参数含义。

2. 关键字参数可以调整顺序

def register(username, email, age):
    print(username, email, age)


register(
    age=20,
    username="Tom",
    email="tom@example.com"
)

关键字参数通过名称匹配,因此可以自由调整顺序。

3. 混合使用时的位置约束

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


# 正确
connect("localhost", 8080, timeout=30)

# 正确
connect("localhost", port=8080, timeout=30)

# 正确
connect(host="localhost", port=8080, timeout=30)

以下形式不合法:

connect(host="localhost", 8080, timeout=30)

因为位置参数不能出现在关键字参数之后。

四、默认参数与位置参数、关键字参数

默认参数允许函数定义时为形参指定默认值。调用时可以省略该参数,也可以显式传递。

1. 默认参数的基本用法

def greet(name, message="Hello"):
    print(f"{message}, {name}!")


greet("Alice")
greet("Alice", "Welcome")
greet("Alice", message="Good morning")

输出:

Hello, Alice!
Welcome, Alice!
Good morning, Alice!

其中:

  • name 是必需参数。
  • message 是具有默认值的参数。
  • 省略 message 时使用默认值。
  • 显式传递 message 时使用调用者提供的值。

2. 默认参数必须遵循定义顺序

普通形参中,带默认值的参数不能出现在没有默认值的参数之前。

错误示例:

def create_user(name="Alice", age):
    pass

这会产生 SyntaxError。

正确写法:

def create_user(name, age=18):
    print(name, age)

3. 默认参数可以通过关键字覆盖

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


connect("localhost")
connect("localhost", 9000)
connect("localhost", timeout=30)
connect("localhost", port=9000, timeout=30)

输出:

localhost 8080 10
localhost 9000 10
localhost 8080 30
localhost 9000 30

当参数较多时,使用关键字参数覆盖默认值,通常比依赖位置更清晰。

五、仅限位置参数与仅限关键字参数

Python 不仅支持位置参数和关键字参数,还允许函数定义者限制参数的传递方式。

Python 3.8 引入了两种重要的参数分隔符:

  • /:表示它前面的参数只能通过位置方式传递。
  • *:表示它后面的普通参数只能通过关键字方式传递。

1. 仅限位置参数

使用 / 可以限制某些形参只能通过位置传递。

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


print(calculate(10, 20))

下面的调用不允许:

calculate(a=10, b=20)

因为 a 和 b 位于 / 之前,只能通过位置参数传递。

完整定义示例:

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


calculate(10, 20, 30)
calculate(10, 20, c=30)

参数分类:

参数 参数类型 调用方式
a 仅限位置参数 calculate(10, 20, 30)
b 仅限位置参数 calculate(10, 20, 30)
c 普通参数 位置或关键字均可

2. 仅限关键字参数

使用 * 可以限制后面的普通形参只能通过关键字传递。

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


create_user("Alice", age=25, city="Tokyo")

以下调用不允许:

create_user("Alice", 25, "Tokyo")

因为 age 和 city 位于 * 之后,必须使用关键字传递。

3. / 与 * 同时使用

两种分隔符可以组合使用,形成更明确的参数接口。

def configure(host, port, /, timeout, *, debug, retry):
    print(host, port, timeout, debug, retry)


configure(
    "localhost",
    8080,
    30,
    debug=True,
    retry=3
)

参数分类:

参数 类型 传递方式
host 仅限位置参数 只能按位置传递
port 仅限位置参数 只能按位置传递
timeout 普通参数 位置或关键字
debug 仅限关键字参数 只能按名称传递
retry 仅限关键字参数 只能按名称传递

4. 参数种类的完整结构

Python 函数参数可以按照以下顺序组织:

def example(
    a, b, /,
    c, d=10,
    *args,
    e, f=20,
    **kwargs
):
    pass

各部分含义:

参数部分 类型 说明
a、b 仅限位置参数 必须按位置传递
c 普通参数 位置或关键字传递
d 带默认值的普通参数 可省略
args 可变位置参数 收集额外的位置参数
e 仅限关键字参数 必须按名称传递
f 带默认值的仅限关键字参数 可省略
kwargs 可变关键字参数 收集额外的关键字参数

调用示例:

def example(
    a, b, /,
    c, d=10,
    *args,
    e, f=20,
    **kwargs
):
    print(a, b, c, d)
    print(args)
    print(e, f)
    print(kwargs)


example(
    1, 2, 3, 4, 5, 6,
    e=7,
    f=8,
    debug=True,
    mode="fast"
)

输出:

1 2 3 4
(5, 6)
7 8
{'debug': True, 'mode': 'fast'}

这里需要注意:

  • *args 收集未被其他参数接收的额外位置参数。
  • **kwargs 收集未被其他参数接收的额外关键字参数。
  • *args 后面的普通形参只能通过关键字传递。
  • **kwargs 必须出现在参数定义的最后。

六、参数解包与位置参数、关键字参数

Python 支持使用 * 和 ** 对可迭代对象、映射对象进行解包,并将其中的数据传递给函数。

1. 使用 * 解包位置参数

当一个列表或元组中的元素需要作为独立的位置参数传递时,可以使用 *。

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


numbers = [10, 20, 30]

print(add(*numbers))

等价于:

add(10, 20, 30)

*numbers 会将可迭代对象中的元素逐个展开为位置参数。

2. 使用 ** 解包关键字参数

当字典中的键与函数形参名称对应时,可以使用 **。

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


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

introduce(**user)

等价于:

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

注意:

  • ** 后面需要提供映射对象,通常是字典。
  • 字典的键必须是字符串,并且要符合关键字名称要求。
  • 如果解包结果与其他实参重复绑定同一个形参,会产生 TypeError。

3. 同时使用 * 和 **

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)

等价于:

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