一、函数参数与返回值概述
函数是 Python 中组织代码和封装业务逻辑的基本单元。一个完整的函数通常围绕三个核心环节展开:
- 输入:通过参数接收外部数据。
- 处理:在函数内部执行计算或业务逻辑。
- 输出:通过返回值将结果交给调用者。
例如:
def calculate_total(price, quantity):
total = price * quantity
return total
result = calculate_total(100, 3)
print(result)
# 300
在这个例子中:
| 组成 | 内容 | 作用 |
|---|---|---|
| 函数名称 | calculate_total |
标识函数 |
| 形式参数 | price、quantity |
接收输入 |
| 函数体 | price * quantity |
执行业务计算 |
| 返回值 | total |
输出计算结果 |
| 实际参数 | 100、3 |
调用时提供的数据 |
函数参数和返回值共同构成函数接口(Function Interface)。
调用者不需要了解函数内部的具体实现,只需要知道应该传入什么数据,以及能够得到什么结果。
二、形式参数与实际参数
Python 函数中有两个容易混淆的概念:形式参数和实际参数。
1. 形式参数 Parameter
形式参数是在函数定义时声明的变量,用于接收调用者传入的数据。
def greet(name):
print(f"你好,{name}!")
这里的 name 就是形式参数。
它相当于函数内部用于引用传入对象的名称。
2. 实际参数 Argument
实际参数是在调用函数时提供的具体值或表达式。
greet("Alice")
这里的 "Alice" 就是实际参数。
函数调用时,Python 会根据参数匹配规则,将实际参数绑定到形式参数。
3. 形式参数与实际参数的区别
| 对比 | 形式参数 | 实际参数 |
|---|---|---|
| 英文 | Parameter | Argument |
| 出现位置 | 函数定义 | 函数调用 |
| 作用 | 声明接收数据的名称 | 提供具体数据 |
| 示例 | def add(a, b) |
add(10, 20) |
4. 一个函数可以定义多个参数
def introduce(name, age, city):
print(f"姓名:{name}")
print(f"年龄:{age}")
print(f"城市:{city}")
introduce("Alice", 25, "Tokyo")
输出:
姓名:Alice
年龄:25
城市:Tokyo
参数之间使用逗号分隔。
调用时,需要保证实际参数能够与函数定义中的参数正确匹配。
三、Python 函数的参数分类
Python 支持多种参数形式,可以满足不同的函数调用需求。
1. 位置参数
位置参数(Positional Parameter)根据参数在函数定义中的位置进行匹配。
def subtract(a, b):
return a - b
result = subtract(20, 5)
print(result)
# 15
匹配关系:
| 形式参数 | 实际参数 |
|---|---|
a |
20 |
b |
5 |
位置参数的顺序非常重要。
print(subtract(20, 5))
# 15
print(subtract(5, 20))
# -15
交换参数位置会改变计算结果。
2. 关键字参数
关键字参数(Keyword Argument)通过参数名称指定传入值。
def introduce(name, age, city):
print(name, age, city)
introduce(
city="Tokyo",
name="Alice",
age=25
)
关键字参数不需要按照函数定义中的位置排列。
优点:
- 提高代码可读性。
- 降低参数顺序错误的风险。
- 适合参数数量较多的函数。
- 可以明确表达每个参数的业务含义。
3. 位置参数与关键字参数混合使用
Python 允许在一次调用中混合使用位置参数和关键字参数。
def create_user(name, age, city):
print(name, age, city)
create_user("Alice", age=25, city="Tokyo")
需要注意:
位置参数必须放在关键字参数之前。
正确:
create_user("Alice", age=25, city="Tokyo")
错误:
# SyntaxError
create_user(name="Alice", 25, city="Tokyo")
因为位置参数不能出现在关键字参数之后。
4. 默认参数
默认参数(Default Parameter)是在函数定义时指定默认值的参数。
如果调用者没有提供该参数,函数就使用默认值。
def greet(name="Guest"):
print(f"Hello, {name}!")
greet()
# Hello, Guest!
greet("Alice")
# Hello, Alice!
默认参数可以让函数调用更加灵活。
默认参数的定义规则
普通必需参数应放在默认参数之前。
正确:
def create_user(name, age=18):
print(name, age)
错误:
# SyntaxError
def create_user(age=18, name):
print(name, age)
5. 可变数量的位置参数
使用 *args 可以让函数接收数量不固定的位置参数。
def calculate_sum(*args):
print(args)
return sum(args)
print(calculate_sum(1, 2, 3))
# 6
print(calculate_sum(10, 20, 30, 40))
# 100
在函数内部,args 是一个元组。
因此可以使用循环、索引和其他元组操作处理这些数据。
def show_items(*args):
for item in args:
print(item)
show_items("Python", "Java", "Go")
适用场景:
- 数量不固定的计算参数。
- 通用工具函数。
- 数据聚合。
- 装饰器和函数包装器。
6. 可变数量的关键字参数
使用 **kwargs 可以接收数量不固定的关键字参数。
def create_user(**kwargs):
print(kwargs)
create_user(
name="Alice",
age=25,
city="Tokyo"
)
输出:
{'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
在函数内部,kwargs 是一个字典。
可以使用 items() 遍历:
def show_user(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
show_user(
name="Alice",
age=25,
city="Tokyo"
)
7. 仅限位置参数
Python 3.8 引入了仅限位置参数语法,使用 / 标记。
位于 / 之前的参数只能通过位置传递。
def calculate(a, b, /):
return a + b
print(calculate(10, 20))
# 30
下面的调用会产生 TypeError:
calculate(a=10, b=20)
这种设计适合:
- 不希望调用者依赖参数名称的 API。
- 需要保护参数名称以便未来调整实现的接口。
- 与某些内置函数的调用方式保持一致。
例如:
def process(value, /):
print(value)
process(100)
8. 仅限关键字参数
使用 * 可以标记后续参数只能通过关键字传递。
def create_user(name, *, age, city):
print(name, age, city)
create_user(
"Alice",
age=25,
city="Tokyo"
)
下面的调用不合法:
create_user("Alice", 25, "Tokyo")
因为 age 和 city 是仅限关键字参数。
仅限关键字参数适合具有多个可选配置项的函数,能够让调用意图更加清晰。
9. 参数类型综合对比
| 参数类型 | 语法 | 传递方式 |
|---|---|---|
| 位置参数 | def f(a) |
按位置 |
| 关键字参数 | f(a=10) |
按名称 |
| 默认参数 | def f(a=10) |
可省略 |
| 可变位置参数 | *args |
接收多个位置参数 |
| 仅限位置参数 | / |
只能按位置传递 |
| 仅限关键字参数 | * |
只能按名称传递 |
| 可变关键字参数 | **kwargs |
接收多个关键字参数 |
四、参数绑定与调用规则
参数绑定(Argument Binding)是函数调用过程中的重要环节。
Python 需要根据函数签名,将实际参数与形式参数建立对应关系。
1. 基本参数绑定
def register(name, age):
print(name, age)
register("Alice", 25)
绑定关系:
name = "Alice"
age = 25
2. 位置参数优先匹配
def show_info(name, age, city):
print(name, age, city)
show_info("Alice", 25, city="Tokyo")
Python 首先根据位置匹配:
name = "Alice"
age = 25
剩余的 city 通过关键字匹配。
3. 同一个参数不能重复赋值
def greet(name):
print(name)
# TypeError
greet("Alice", name="Bob")
这里 name 已经通过位置参数获得了值,又通过关键字参数获得第二个值,因此产生参数绑定错误。
4. 缺少必需参数
def add(a, b):
return a + b
# TypeError
add(10)
参数 b 没有得到赋值。
5. 出现多余参数
def greet(name):
print(name)
# TypeError
greet("Alice", "Bob")
函数只接受一个位置参数,却传入了两个。
6. 参数绑定错误的常见类型
| 错误类型 | 原因 |
|---|---|
| Missing required argument | 缺少必需参数 |
| Too many positional arguments | 位置参数过多 |
| Unexpected keyword argument | 关键字名称不匹配 |
| Multiple values for argument | 同一参数被重复赋值 |
| Positional argument follows keyword argument | 位置参数出现在关键字参数之后 |
五、默认参数的深入理解
默认参数看似简单,但其中存在一个非常重要的机制:默认值在函数定义执行时求值,而不是每次调用时重新求值。
1. 默认参数的求值时机
def greet(name="Guest"):
print(name)
执行 def 语句时,默认值 "Guest" 就已经确定。
可以通过 __defaults__ 查看位置参数默认值:
print(greet.__defaults__)
# ('Guest',)
2. 可变默认参数陷阱
错误示例:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("Python"))
# ['Python']
print(add_item("Java"))
# ['Python', 'Java']
为什么第二次调用仍然保留第一次的数据?
因为列表是在函数定义时创建的。
后续没有传入 items 时,函数会继续使用同一个默认列表对象。
可以通过下面的方式观察:
def collect(item, items=[]):
items.append(item)
return items
print(collect.__defaults__)
3. 使用 None 解决可变默认参数问题
推荐写法:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("Python"))
# ['Python']
print(add_item("Java"))
# ['Java']
每次调用时,如果没有传入列表,就在函数内部创建新的列表。
4. 使用默认参数的其他注意事项
默认参数也可以是不可变对象、函数对象和其他适合复用的对象。
def calculate(value, multiplier=2):
return value * multiplier
但需要注意:
- 默认值只在函数定义时求值。
- 默认参数对象可能在多次调用之间共享。
- 可变默认参数容易产生意外状态。
- 如果需要动态生成默认值,应在函数体内部完成。
- 不要依赖修改
__defaults__来控制业务行为。
六、参数传递机制
Python 的参数传递经常被描述为值传递或引用传递,但这两种传统说法都不能完整表达 Python 的实际语义。
更准确的理解是:函数参数接收的是传入对象的引用绑定,调用者和被调用者可以通过不同名称引用同一个对象。
这种模型通常称为共享对象传递(Call by Sharing)。
1. 传入不可变对象
def change_number(number):
number = 100
value = 10
change_number(value)
print(value)
# 10
函数内部的 number 和外部的 value 最初引用同一个整数对象。
但是执行:
number = 100
只是让局部名称 number 重新绑定到另一个整数对象。
它不会改变外部名称 value 的绑定关系。
2. 传入可变对象
def add_item(items):
items.append("Python")
languages = ["Java", "Go"]
add_item(languages)
print(languages)
# ['Java', 'Go', 'Python']
这里参数 items 和外部变量 languages 引用同一个列表对象。
调用 append() 修改了这个共享列表,因此外部也能观察到变化。
3. 修改对象与重新绑定名称
def modify(items):
items.append(100)
def rebind(items):
items = [100, 200]
numbers = [1, 2, 3]
modify(numbers)
print(numbers)
# [1, 2, 3, 100]
rebind(numbers)
print(numbers)
# [1, 2, 3, 100]
两种操作有本质区别:
| 操作 | 行为 | 外部影响 |
|---|---|---|
items.append(100) |
修改共享对象 | 外部可见 |
items.clear() |
修改共享对象 | 外部可见 |
items = [100, 200] |
重新绑定局部名称 | 不改变外部绑定 |
items = None |
重新绑定局部名称 | 不改变外部绑定 |
4. 参数传递流程图
flowchart TD
A["调用函数"] --> B["求值实际参数"]
B --> C["参数名称绑定到传入对象"]
C --> D{"函数如何操作参数"}
D -->|"修改对象"| E["改变共享对象状态"]
D -->|"重新绑定名称"| F["改变局部名称绑定"]
E --> G["调用者可以观察到对象变化"]
F --> H["调用者原有绑定保持不变"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5. 如何避免意外修改外部数据
如果函数不应该改变调用者提供的数据,可以根据实际需求复制对象。
浅拷贝:
def process_items(items):
copied = items.copy()
copied.append(100)
return copied
对于嵌套结构,浅拷贝只复制外层容器,内部对象仍然可能共享。
需要完全隔离嵌套可变对象时,可以考虑 copy.deepcopy(),但必须评估对象类型、资源和复制成本。
七、参数解包与传递
Python 支持使用 * 和 ** 在函数调用时解包序列和映射对象。
1. 使用 * 解包序列
def add(a, b, c):
return a + b + c
numbers = [10, 20, 30]
result = add(*numbers)
print(result)
# 60
*numbers 会将列表中的元素分别作为位置参数传入。
也可以解包元组:
values = (10, 20, 30)
print(add(*values))
# 60
2. 使用 ** 解包字典
def introduce(name, age, city):
print(name, age, city)
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
introduce(**user)
字典中的键会作为关键字参数名称,字典中的值作为对应参数的实际值。
3. 同时使用 * 和 **
def create_user(name, age, city, role):
print(name, age, city, role)
args = ("Alice", 25)
kwargs = {
"city": "Tokyo",
"role": "Developer"
}
create_user(*args, **kwargs)
这种方式常见于:
- 通用函数包装。
- 装饰器。
- API 参数转发。
- 框架内部的函数调用。
4. 解包参数与收集参数的区别
需要注意,函数定义和函数调用中的星号含义不同。
函数定义:
def process(*args, **kwargs):
print(args)
print(kwargs)
这里的 *args 和 **kwargs 用于收集参数。
函数调用:
values = [1, 2, 3]
options = {"name": "Alice"}
process(*values, **options)
这里的 * 和 ** 用于解包参数。
5. 解包时的常见错误
参数数量不匹配
def add(a, b):
return a + b
numbers = [1, 2, 3]
# TypeError
add(*numbers)
字典键与函数参数不匹配
def greet(name):
print(name)
user = {"username": "Alice"}
# TypeError
greet(**user)
同一个参数被重复传递
def greet(name):
print(name)
# TypeError
greet("Alice", **{"name": "Bob"})
八、函数的返回值
返回值(Return Value)是函数执行后交给调用者的结果。
Python 使用 return 语句返回对象。
1. return 的基本语法
def function_name():
return expression
例如:
def add(a, b):
return a + b
result = add(10, 20)
print(result)
# 30
返回值可以是任何 Python 对象,包括:
- 整数。
- 浮点数。
- 字符串。
- 布尔值。
- 列表。
- 元组。
- 字典。
- 集合。
- 函数对象。
- 自定义对象。
- 生成器对象。
2. return 会结束当前函数调用
def check_number(number):
if number > 0:
return "正数"
return "非正数"
print(check_number(10))
# 正数
函数执行到 return 后,会立即结束当前调用。
后面的语句不会继续执行。
def test():
print("开始")
return "完成"
print("结束")
test()
输出:
开始
3. 没有 return 时返回 None
如果函数没有执行显式 return,正常结束时会隐式返回 None。
def greet():
print("Hello")
result = greet()
print(result)
# None
以下两种写法的返回结果相同:
def first():
return
def second():
return None
4. return 与 print 的区别
print() 用于输出内容,return 用于返回结果。
def add_with_print(a, b):
print(a + b)
def add_with_return(a, b):
return a + b
result1 = add_with_print(10, 20)
result2 = add_with_return(10, 20)
print(result1)
# None
print(result2)
# 30
对比:
| 对比 | return | |
|---|---|---|
| 核心作用 | 显示内容 | 返回对象 |
| 是否结束函数 | 否 | 是 |
| 是否能直接作为计算结果 | 否 | 是 |
| 是否改变调用者的变量绑定 | 不会 | 由调用者决定如何使用结果 |
| 主要用途 | 调试和输出 | 函数结果传递 |
工程实践中,业务计算函数通常应该返回结果,而不是只负责打印结果。
5. 函数可以返回多个值
Python 可以在 return 后面使用逗号分隔多个表达式。
def calculate(a, b):
total = a + b
difference = a - b
return total, difference
result = calculate(20, 10)
print(result)
# (30, 10)
实际上,多个返回值会被打包为一个元组。
因此可以使用序列解包接收:
total, difference = calculate(20, 10)
print(total)
# 30
print(difference)
# 10
也可以只接收其中一部分:
total, _ = calculate(20, 10)
print(total)
# 30
这里的 _ 只是一个常见的占位名称,并不是特殊的忽略语法。
6. 条件返回
函数可以根据不同条件返回不同结果。
def get_grade(score):
if score >= 90:
return "优秀"
if score >= 80:
return "良好"
if score >= 60:
return "及格"
return "不及格"
条件分支中使用 return,可以让函数在满足条件时提前结束。
7. 返回容器对象
函数可以将多个相关数据组织成字典返回。
def get_user():
return {
"id": 1001,
"name": "Alice",
"age": 25
}
user = get_user()
print(user["name"])
# Alice
返回字典适合表达字段较多、具有明确名称的结果。
如果结果结构固定,也可以考虑使用 dataclass 或 NamedTuple。
8. 返回函数对象
Python 中函数也是对象,因此函数可以作为另一个函数的返回值。
def get_operation():
def add(a, b):
return a + b
return add
operation = get_operation()
print(operation(10, 20))
# 30
这种机制是闭包、高阶函数和装饰器等高级特性的基础。
九、返回值的类型与设计
返回值不仅是函数计算的结果,也是函数接口设计的重要组成部分。
1. 返回单个基本数据类型
def get_age():
return 25
age = get_age()
适合返回单一、明确的结果。
2. 返回布尔值
def is_adult(age):
return age >= 18
print(is_adult(20))
# True
这类函数通常用于判断、校验和条件分支。
命名上可以使用 is_、has_、can_ 等前缀。
3. 返回列表
def get_active_users():
return ["Alice", "Bob", "Charlie"]
users = get_active_users()
适合返回数量不固定、顺序有意义的数据集合。
4. 返回字典
def get_product():
return {
"id": 1001,
"name": "Keyboard",
"price": 199.9
}
适合返回字段较多的结构化数据。
5. 返回 None 表示无结果
def find_user(user_id):
if user_id == 1:
return "Alice"
return None
user = find_user(100)
None 常用于表示不存在、没有结果或没有提供数据。
调用者需要明确处理这种情况:
user = find_user(100)
if user is None:
print("用户不存在")
else:
print(user)
使用 is None 判断通常比 == None 更合适。
6. 不要混淆 None 与空容器
以下结果表达的含义不同:
def return_none():
return None
def return_empty_list():
return []
def return_empty_dict():
return {}
def return_empty_string():
return ""
| 返回值 | 含义示例 |
|---|---|
None |
没有结果或未提供 |
[] |
有一个列表结果,但当前没有元素 |
{} |
有一个字典结果,但当前没有字段 |
"" |
返回了空字符串 |
函数接口应该明确这些值的业务含义。
7. 返回值的选择原则
| 业务需求 | 推荐返回值 |
|---|---|
| 单个计算结果 | 基本数据类型 |
| 成功或失败判断 | bool 或明确的结果对象 |
| 多个同类元素 | list、tuple |
| 多个命名字段 | dict、dataclass |
| 没有查询结果 | None 或明确的空结果 |
| 惰性数据流 | 生成器或迭代器 |
| 多种业务结果 | 结构化结果对象或异常机制 |
不要为了图省事,让一个函数在不同情况下随意返回整数、字符串、列表和 None,却不说明这些结果分别代表什么。
十、返回值与异常的区别
函数无法正常完成任务时,可以通过返回值表达结果,也可以通过异常表达错误。
这两种方式需要根据业务语义选择。
1. 使用返回值表示正常结果
def divide(a, b):
if b == 0:
return None
return a / b
调用者需要检查结果:
result = divide(10, 0)
if result is None:
print("无法计算")
else:
print(result)
2. 使用异常表达错误
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
调用:
try:
result = divide(10, 0)
except ValueError as exc:
print("计算失败:", exc)
3. 返回值与异常对比
| 对比 | 返回值 | 异常 |
|---|---|---|
| 主要用途 | 表达正常结果或可预期状态 | 表达异常情况 |
| 控制流程 | 正常返回给调用者 | 沿调用栈向上传播 |
| 调用者处理 | 判断返回结果 | 使用 try/except |
| 适合场景 | 查询无结果、状态判断 | 参数非法、资源不可用等 |
例如:
- 查询用户不存在,可以根据 API 约定返回
None。 - 用户输入格式非法,可以抛出
ValueError。 - 文件不存在,可以让
FileNotFoundError传播或在适当层处理。 - 网络连接失败,可以抛出相应网络异常。
重要的是让调用者能够准确理解函数的行为。
十一、函数参数与返回值的类型注解
Python 支持通过类型注解描述参数和返回值的预期类型。
1. 基本语法
def function_name(
parameter: ParameterType
) -> ReturnType:
return result
例如:
def add(a: int, b: int) -> int:
return a + b
其中:
a: int:参数 a 预期是整数。b: int:参数 b 预期是整数。-> int:函数预期返回整数。
2. 字符串参数与返回值
def greet(name: str) -> str:
return f"Hello, {name}"
3. 列表参数与返回值
def get_positive_numbers(
numbers: list[int]
) -> list[int]:
return [
number
for number in numbers
if number > 0
]
4. 字典参数与返回值
def get_user(
user_id: int
) -> dict[str, str | int]:
return {
"id": user_id,
"name": "Alice"
}
5. 联合类型
如果参数或返回值可能有多种类型,可以使用联合类型。
def normalize(value: int | float) -> float:
return float(value)
Python 3.10 起支持 | 表示联合类型。
6. 可选返回值
如果函数可能返回指定类型,也可能返回 None,可以这样注解:
def find_user(user_id: int) -> str | None:
if user_id == 1:
return "Alice"
return None
在较旧版本中,也可以使用:
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
if user_id == 1:
return "Alice"
return None
7. 使用 Any 表示动态类型
from typing import Any
def process_data(value: Any) -> Any:
return value
Any 表示类型检查器不对该对象施加通常的静态类型约束。
它适合处理动态数据,但不应该在所有函数中滥用,否则类型注解的价值会降低。
8. 使用 Callable 描述函数参数
如果一个函数接收另一个函数作为参数,可以使用 Callable 描述。
from collections.abc import Callable
def execute(
operation: Callable[[int, int], int],
a: int,
b: int
) -> int:
return operation(a, b)
def add(a: int, b: int) -> int:
return a + b
print(execute(add, 10, 20))
# 30
9. 类型注解不会自动强制转换
def add(a: int, b: int) -> int:
return a + b
print(add("Hello", "Python"))
# HelloPython
Python 默认不会因为实际参数不符合注解,就自动拒绝调用。
类型注解主要服务于:
- IDE 自动补全。
- 静态类型检查。
- 代码文档。
- 接口设计。
- 代码维护。