Python 中的 *args 和 **kwargs

概述

*args**kwargs 是 Python 中用于处理可变数量参数的语法,它们让函数能够接受任意数量的位置参数和关键字参数。

*args(可变位置参数)

作用

  • 接收任意数量的位置参数

  • 将这些参数作为元组传递给函数

基本用法

python 复制代码
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')

输出:

python 复制代码
参数类型: <class 'tuple'>
参数值: (1, 2, 3)
第 1 个参数: 1
第 2 个参数: 2
第 3 个参数: 3
实际应用示例
python 复制代码
def calculate_sum(*numbers):
    """计算任意数量数字的和"""
    return sum(numbers)

print(calculate_sum(1, 2, 3))        # 输出: 6
print(calculate_sum(10, 20, 30, 40)) # 输出: 100

**kwargs(可变关键字参数)

作用

  • 接收任意数量的关键字参数

  • 将这些参数作为字典传递给函数

基本用法

python 复制代码
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)
输出:
python 复制代码
参数类型: <class 'dict'>
参数值: {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
name: Alice
age: 25
city: Beijing

实际应用示例

python 复制代码
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 profile

user1 = 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

完整语法

python 复制代码
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)

输出:

python 复制代码
必需参数: hello
额外位置参数: (1, 2, 3)
额外关键字参数: {'name': 'Alice', 'age': 25}

实际应用:装饰器

python 复制代码
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 result
    return wrapper

@logger
def multiply_numbers(a, b, c=1):
    return a * b * c

# 测试
multiply_numbers(2, 3)
multiply_numbers(2, 3, c=4)
复制代码

参数解包

使用 * 解包序列

python 复制代码
def print_coordinates(x, y, z):
    print(f"坐标: ({x}, {y}, {z})")

coordinates = [10, 20, 30]
print_coordinates(*coordinates)  # 相当于 print_coordinates(10, 20, 30)
复制代码

使用 ** 解包字典

python 复制代码
def introduce_person(name, age, occupation):py
    print(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
复制代码
相关推荐
曲幽15 分钟前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健15 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞17 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽19 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img