精通Python函数参数:位置、关键字与默认参数
精通Python函数参数
探索如何设计接受可变数量参数的Python函数——利用默认值、关键字参数和任意参数编写更简洁、适应性更强的代码。
视频:Python函数参数:位置、关键字与默认
参数
用户定义函数主题涵盖定义和调用函数。调用与预期签名不匹配会报错。例如:
def greet(name, msg):
"""This function greets the person with the provided message."""
print("Hello", name + ", " + msg)
greet("Monica", "Good morning!")
输出
Hello Monica, Good morning!
greet() 接受两个参数。正确数量参数调用顺利运行;否则解释器抛出清晰的 TypeError。
>>> greet("Monica") # 仅一个参数
TypeError: greet() missing 1 required positional argument: 'msg'
>>> greet() # 无参数 TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'
可变函数参数
Python提供灵活方式接受可变数量参数。下文介绍三种常见模式。
Python默认参数
参数可用赋值运算符(=)给默认值。下例演示可选消息默认为“Good morning!”:
def greet(name, msg="Good morning!"):
"""
This function greets the person with the provided message.
If the message is not supplied, it defaults to "Good morning!".
"""
print("Hello", name + ", " + msg)
greet("Kate")
greet("Bruce", "How do you do?")
输出
Hello Kate, Good morning! Hello Bruce, How do you do?
此定义中 name 必选,msg 可选。有默认参数时,后续参数必须也有默认值;否则 SyntaxError。
def greet(msg = "Good morning!", name): pass
SyntaxError: non-default argument follows default argument
Python关键字参数
Python允许调用者按名称指定参数,实现位置顺序灵活。同一 greet() 可这样调用:
# 2个关键字参数
greet(name="Bruce", msg="How do you do?")
# 2个关键字参数(乱序)
greet(msg="How do you do?", name="Bruce")
# 1位置、1关键字参数
greet("Bruce", msg="How do you do?")
混合位置和关键字参数仅当所有位置参数在关键字参数前才允许;否则 SyntaxError。
greet(name="Bruce","How do you do?")
SyntaxError: non-keyword arg after keyword arg
Python任意参数
设计时未知参数数量时,用星号(*)捕获为元组:
def greet(*names):
"""Greets each name in the supplied tuple."""
for name in names:
print("Hello", name)
greet("Monica", "Luke", "Steve", "John")
输出
Hello Monica Hello Luke Hello Steve Hello John
函数内 names 为包含所有传入参数的元组,可迭代或按需处理。
Python