Python函数参数中确实有两个特殊的分隔符:
/:仅位置参数 ,放在/之前的参数只能按位置传递。*:仅关键字参数 ,放在*之后的参数只能按关键字传递。
他们可以单独使用,也可以组合使用,完整语法如下
python
def func(pos_only, /, normal, *, kw_only):
pass

| 区域 | 传参方式 | 示例 |
|---|---|---|
a, b |
只能按位置 | func(1, 2, ...) |
c, d |
位置或关键字均可 | func(1, 2, 3, 4, ...) 或 func(1, 2, c=3, d=4, ...) |
e, f |
只能按关键字 | ..., e=5, f=6) |
(一)/ 之前仅位置参数
/ 之前的参数只能使用位置传参禁止使用关键字传参。 它在Python3.8版本引入。
python
def greet(name, /, greeting="Hello"):
print(f"{greeting}, {name}!")
# 正确
greet("Alice") # Hello, Alice!
greet("Alice", "Hi") # Hi, Alice!
greet("Alice", greeting="Hi") # Hi, Alice!
# 错误!name 是仅位置参数
greet(name="Alice") # TypeError: greet() got some positional-only arguments passed as keyword arguments: 'name'
(二)* 之后仅关键字参数
* 之后的参数必须使用关键字传参。
python
def create_user(name, *, age, email=None):
...
# 正确
create_user("Alice", age=30)
create_user("Alice", age=30, email="a@b.com")
# 错误!age 和 email 是仅关键字参数
create_user("Alice", 30) # TypeError: takes 2 positional arguments but 3 were given
create_user("Alice", 30, "a@b.com") # 同上
【注】/ 和 * 本身不是参数,它们只是分隔符。/ 不能在 * 后面。lambda 不支持 /,但 lambda 支持 *