Python 中的 *args 和 **kwargs
概述
*args 和 **kwargs 是 Python 中用于处理可变数量参数的语法,它们让函数能够接受任意数量的位置参数和关键字参数。
*args(可变位置参数)
作用
接收任意数量的位置参数
将这些参数作为元组传递给函数
基本用法
def function_with_args(*args):print(f"参数类型: {type(args)}")print(f"参数值: {args}")for i, arg in enumerate(args):print(f"第 {i+1} 个参数: {arg}")# 调用示例
function_with_args(1, 2, 3)
function_with_args('a', 'b', 'c', 'd')输出:
参数类型: <class 'tuple'>
参数值: (1, 2, 3)
第 1 个参数: 1
第 2 个参数: 2
第 3 个参数: 3
实际应用示例
def calculate_sum(*numbers):"""计算任意数量数字的和"""return sum(numbers)print(calculate_sum(1, 2, 3)) # 输出: 6
print(calculate_sum(10, 20, 30, 40)) # 输出: 100**kwargs(可变关键字参数)
作用
接收任意数量的关键字参数
将这些参数作为字典传递给函数
基本用法
def function_with_kwargs(**kwargs):print(f"参数类型: {type(kwargs)}")print(f"参数值: {kwargs}")for key, value in kwargs.items():print(f"{key}: {value}")# 调用示例
function_with_kwargs(name="Alice", age=25, city="Beijing")
function_with_kwargs(product="Laptop", price=999, brand="Dell", in_stock=True)
输出:
参数类型: <class 'dict'>
参数值: {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
name: Alice
age: 25
city: Beijing实际应用示例
def create_user_profile(**user_info):"""创建用户配置文件"""profile = {'username': user_info.get('username', 'anonymous'),'email': user_info.get('email', ''),'age': user_info.get('age', 0),'role': user_info.get('role', 'user')}# 添加额外的用户信息profile.update(user_info)return profileuser1 = create_user_profile(username="alice", email="alice@example.com")
user2 = create_user_profile(username="bob", age=30, role="admin", department="IT")
print(user1)
print(user2)组合使用 *args 和 **kwargs
完整语法
def complex_function(required_arg, *args, **kwargs):print(f"必需参数: {required_arg}")print(f"额外位置参数: {args}")print(f"额外关键字参数: {kwargs}")# 调用示例
complex_function("hello", 1, 2, 3, name="Alice", age=25)输出:
必需参数: hello
额外位置参数: (1, 2, 3)
额外关键字参数: {'name': 'Alice', 'age': 25}实际应用:装饰器
def logger(func):"""记录函数调用信息的装饰器"""def wrapper(*args, **kwargs):print(f"调用函数: {func.__name__}")print(f"位置参数: {args}")print(f"关键字参数: {kwargs}")result = func(*args, **kwargs)print(f"返回值: {result}")return resultreturn wrapper@logger
def multiply_numbers(a, b, c=1):return a * b * c# 测试
multiply_numbers(2, 3)
multiply_numbers(2, 3, c=4)参数解包
使用 * 解包序列
def print_coordinates(x, y, z):print(f"坐标: ({x}, {y}, {z})")coordinates = [10, 20, 30]
print_coordinates(*coordinates) # 相当于 print_coordinates(10, 20, 30)使用 ** 解包字典
def introduce_person(name, age, occupation):pyprint(f"{name} is {age} years old and works as a {occupation}")person_info = {"name": "Alice", "age": 25, "occupation": "engineer"}
introduce_person(**person_info) # 相当于 introduce_person(name="Alice", age=25, occupation="enginee