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
复制代码
相关推荐
Easonmax2 小时前
用 Rust 打造可复现的 ASCII 艺术渲染器:从像素到字符的完整工程实践
开发语言·后端·rust
lsx2024062 小时前
Rust 宏:深入理解与高效使用
开发语言
百锦再2 小时前
选择Rust的理由:从内存管理到抛弃抽象
android·java·开发语言·后端·python·rust·go
yaoxin5211232 小时前
238. Java 集合 - 使用 ListIterator 遍历 List 元素
java·python·list
小羊失眠啦.2 小时前
深入解析Rust的所有权系统:告别空指针和数据竞争
开发语言·后端·rust
Dxxyyyy2 小时前
零基础学JAVA--Day32(ArrayList底层+Vector+LinkedList)
java·开发语言
nvd112 小时前
python 后端流式处理 LLM 响应数据详解
开发语言·python
蓝天智能2 小时前
Qt 的字节序转换
开发语言·qt
F_D_Z2 小时前
【解决办法】报错Found dtype Long but expected Float
人工智能·python