一、什么是默认参数?
默认参数(Default Arguments)是指在定义函数时,为形参指定一个默认值。当调用函数时没有提供对应实参,Python 就会使用这个默认值。
1. 默认参数的基本语法
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice")
greet("Bob", "Welcome")
输出:
Hello, Alice!
Welcome, Bob!
其中:
name是必需参数,调用时必须提供。message是默认参数,调用时可以省略。- 省略
message时,使用默认值"Hello"。 - 显式传递
message时,使用调用者提供的值。
2. 默认参数的定义规则
普通参数中,带默认值的参数必须放在没有默认值的参数之后。
正确写法:
def create_user(name, age=18, city="Tokyo"):
print(name, age, city)
create_user("Alice")
create_user("Bob", 25)
create_user("Charlie", 30, "Osaka")
错误写法:
def create_user(name="Alice", age):
pass
这会产生 SyntaxError,因为没有默认值的普通参数不能出现在带默认值的普通参数之后。
不过,Python 还支持仅限关键字参数等其他参数形式,它们有各自的排列规则。
二、Python 默认参数的求值时机
这是理解默认参数陷阱最重要的知识点。
Python 默认参数表达式在执行函数定义语句时求值,而不是在每次调用函数时重新求值。
1. 默认参数只初始化一次
def show_time(value=10):
print(value)
show_time()
show_time()
show_time()
三次调用都会使用 10。
对于不可变对象,这种行为通常不会产生问题。
但是,如果默认值是列表、字典或集合等可变对象,就可能出现意料之外的结果。
2. 使用对象身份观察默认参数
def process(items=[]):
print(id(items))
items.append(1)
print(items)
process()
process()
process()
可能输出:
140000000000000
[1]
140000000000000
[1, 1]
140000000000000
[1, 1, 1]
这里的内存地址仅用于示意,实际地址由运行环境决定。
可以看到:
- 多次调用使用的是同一个列表对象。
- 每次调用都会修改这个列表。
- 后续调用能够看到之前调用留下的数据。
原因是默认参数中的列表在函数定义时创建,函数调用时只是继续使用这个对象。
3. 默认参数对象的生命周期
def append_item(item, container=[]):
container.append(item)
return container
print(append_item("A"))
print(append_item("B"))
print(append_item("C"))
输出:
['A']
['A', 'B']
['A', 'B', 'C']
执行过程:
flowchart TD
A["执行函数定义"] --> B["创建默认列表"]
B --> C["保存默认参数对象"]
C --> D["第一次调用函数"]
D --> E["使用默认列表并追加元素"]
E --> F["第二次调用函数"]
F --> G["继续使用同一个列表"]
G --> H["追加新元素"]
H --> I["后续调用继续共享该对象"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
这里的关键不是函数是否被重复调用,而是默认参数始终引用同一个可变对象。
三、什么是可变默认参数陷阱?
可变默认参数陷阱(Mutable Default Argument Trap)是指函数使用列表、字典、集合等可变对象作为默认参数时,多次调用可能共享同一个对象,导致数据在调用之间意外保留。
1. 列表作为默认参数
错误示例:
def add_item(item, items=[]):
items.append(item)
return items
result1 = add_item("Python")
result2 = add_item("Java")
result3 = add_item("Go")
print(result1)
print(result2)
print(result3)
输出:
['Python', 'Java', 'Go']
['Python', 'Java', 'Go']
['Python', 'Java', 'Go']
为什么三个变量得到相同内容?
因为 result1、result2、result3 都引用同一个列表对象。
可以通过对象身份进行验证:
print(result1 is result2)
print(result2 is result3)
输出:
True
True
2. 字典作为默认参数
错误示例:
def update_config(key, value, config={}):
config[key] = value
return config
config1 = update_config("host", "localhost")
config2 = update_config("port", 8080)
print(config1)
print(config2)
输出:
{'host': 'localhost', 'port': 8080}
{'host': 'localhost', 'port': 8080}
第二次调用修改的不是一个全新的字典,而是第一次调用使用过的字典。
这种问题在配置管理、缓存、数据处理等场景中尤其隐蔽。
3. 集合作为默认参数
def add_permission(permission, permissions=set()):
permissions.add(permission)
return permissions
print(add_permission("read"))
print(add_permission("write"))
print(add_permission("delete"))
输出:
{'read'}
{'read', 'write'}
{'read', 'write', 'delete'}
集合也属于可变对象,因此同样存在共享问题。
4. 嵌套可变对象同样存在风险
即使外层容器结构看起来比较简单,只要默认对象中包含可变对象,仍然可能产生共享状态。
def add_user(name, users={"members": []}):
users["members"].append(name)
return users
print(add_user("Alice"))
print(add_user("Bob"))
输出:
{'members': ['Alice']}
{'members': ['Alice', 'Bob']}
问题来自默认字典及其内部列表在多次调用之间被共享。
四、为什么不可变默认参数通常是安全的?
Python 中常见的不可变对象包括:
- 整数
int - 浮点数
float - 布尔值
bool - 字符串
str - 元组
tuple - 冻结集合
frozenset None
它们不能通过普通的原地操作修改自身状态,因此通常适合作为默认参数。
1. 使用整数作为默认参数
def calculate(value, multiplier=2):
return value * multiplier
print(calculate(10))
print(calculate(10, 3))
输出:
20
30
这里没有共享状态被修改的问题。
2. 使用字符串作为默认参数
def greet(name, prefix="Hello"):
return f"{prefix}, {name}"
print(greet("Alice"))
print(greet("Bob"))
每次调用都使用相同的默认字符串对象,但字符串本身不可变,因此不会发生默认参数被原地修改的问题。
3. 元组需要特别注意
元组是不可变序列,但并不意味着元组内部的所有对象都不可变。
def process(data=(1, [])):
data[1].append(100)
return data
print(process())
print(process())
输出:
(1, [100])
(1, [100, 100])
虽然元组本身不能修改元素引用,但其中的列表仍然可以修改。
因此,判断默认参数是否安全,不能只看最外层容器是否可变,还需要检查内部对象。
五、正确解决可变默认参数陷阱
最推荐的解决方案是使用 None 作为默认值,在函数内部创建新的可变对象。
1. 使用 None 作为默认参数
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
result1 = add_item("Python")
result2 = add_item("Java")
result3 = add_item("Go")
print(result1)
print(result2)
print(result3)
输出:
['Python']
['Java']
['Go']
每次调用都创建新的列表,因此不同调用之间不会共享默认列表。
2. 使用 None 初始化字典
def update_config(key, value, config=None):
if config is None:
config = {}
config[key] = value
return config
config1 = update_config("host", "localhost")
config2 = update_config("port", 8080)
print(config1)
print(config2)
输出:
{'host': 'localhost'}
{'port': 8080}
每次没有传入 config 时,函数都会创建新的字典。
3. 使用 None 初始化集合
def add_permission(permission, permissions=None):
if permissions is None:
permissions = set()
permissions.add(permission)
return permissions
print(add_permission("read"))
print(add_permission("write"))
输出:
{'read'}
{'write'}
4. None 方案的执行流程
flowchart TD
A["调用函数"] --> B{"是否传入容器参数"}
B -->|是| C["使用调用者传入的对象"]
B -->|否| D["默认参数为 None"]
D --> E["在函数内部创建新容器"]
C --> F["执行业务逻辑"]
E --> F
F --> G["返回处理结果"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
这种写法还有一个重要优势:调用者可以主动传入已有容器,让函数修改这个容器。
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
existing = ["Java"]
result = add_item("Python", existing)
print(result)
print(existing)
输出:
['Java', 'Python']
['Java', 'Python']
这里函数没有创建新列表,而是使用调用者传入的列表。
六、可变默认参数与显式共享状态
可变默认参数并非在任何情况下都不能使用。
有时开发者确实希望多个调用共享某个对象,例如缓存、计数器或状态记录。
但这类行为应当明确设计,而不是意外依赖默认参数的求值机制。