全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 5 分钟 ✍️ juanwangdev

Python默认参数

默认参数允许函数调用时省略某些参数,提高函数灵活性。

基本语法

设置默认值

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

# 调用方式
greet("Alice")              # Alice, Hello
greet("Bob", "Hi")          # Bob, Hi
greet("Charlie", message="Hey")  # Charlie, Hey

多个默认参数

Python
def create_profile(name, age=18, city="Beijing"):
    return f"{name}, {age}, {city}"

create_profile("Alice")                      # Alice, 18, Beijing
create_profile("Bob", 25)                   # Bob, 25, Beijing
create_profile("Charlie", 30, "Shanghai")   # Charlie, 30, Shanghai
create_profile("Dave", city="Shenzhen")     # Dave, 18, Shenzhen

求值时机陷阱

关键:默认值在函数定义时求值一次

陷阱示例:可变默认参数

Python
# 错误做法
def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] - 意外!列表被共享
print(add_item(3))  # [1, 2, 3]

原因分析

Python
def add_item(item, items=[]):
    # items 默认值在函数定义时创建
    # 所有调用共享同一个列表对象
    items.append(item)
    return items

正确做法

使用 None 作为默认值

Python
def add_item(item, items=None):
    if items is None:
        items = []  # 每次调用创建新列表
    items.append(item)
    return items

print(add_item(1))  # [1]
print(add_item(2))  # [2] - 正确,独立列表

其他可变类型同理

Python
# 字典默认值
def set_config(key, value, config=None):
    if config is None:
        config = {}
    config[key] = value
    return config

# 集合默认值
def add_numbers(num, numbers=None):
    if numbers is None:
        numbers = set()
    numbers.add(num)
    return numbers

默认参数位置规则

必须在非默认参数之后

Python
# 正确
def func(a, b, c=1, d=2):
    pass

# 错误
# def func(a=1, b, c):  # SyntaxError
#     pass

默认参数顺序

Python
def func(pos1, pos2, default1=1, default2=2):
    pass

func(1, 2)           # 使用所有默认值
func(1, 2, 3)        # default1=3, default2=2
func(1, 2, 3, 4)     # default1=3, default2=4

实际应用

简化常用场景

Python
def connect(host, port=3306, timeout=30):
    print(f"Connecting to {host}:{port}, timeout={timeout}")

connect("localhost")                    # 使用默认端口和超时
connect("localhost", 3307)              # 指定端口
connect("localhost", timeout=60)        # 指定超时,端口用默认

配置函数

Python
def format_text(text, uppercase=False, prefix="", suffix=""):
    result = text
    if uppercase:
        result = result.upper()
    return f"{prefix}{result}{suffix}"

format_text("hello")                          # hello
format_text("hello", uppercase=True)          # HELLO
format_text("hello", prefix="[", suffix="]")  # [hello]

要点总结

  1. 默认参数使函数调用更灵活
  2. 默认值在函数定义时求值,只求值一次
  3. 可变默认参数(列表、字典)会导致共享问题
  4. 使用 None 作为可变参数的默认值
  5. 默认参数必须放在非默认参数之后

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python递归函数
下一篇 → Python finally子句
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库