Python案例怎么运用不定长参数?

wen python案例 12

本文目录导读:

Python案例怎么运用不定长参数?

  1. 基础案例:计算任意数量数字的平均值
  2. 实际应用:学生成绩管理系统
  3. 模拟打印机功能
  4. 组合使用:装饰器记录函数调用
  5. 灵活性案例:数据处理函数
  6. 实际项目案例:API请求构建器

在Python中,不定长参数是非常实用的特性,特别是在你不知道函数需要接收多少个参数的情况下,我来通过几个典型案例详细说明:

基础案例:计算任意数量数字的平均值

def calculate_average(*args):
    """
    计算任意数量数字的平均值
    *args 可以接收任意多个位置参数
    """
    if len(args) == 0:
        return 0
    total = sum(args)
    average = total / len(args)
    return average
# 使用示例
print(calculate_average(1, 2, 3, 4, 5))      # 输出: 3.0
print(calculate_average(10, 20))             # 输出: 15.0
print(calculate_average())                   # 输出: 0

实际应用:学生成绩管理系统

def student_info(name, **kwargs):
    """
    记录学生的各种信息
    **kwargs 可以接收任意多个关键字参数
    """
    info = {
        'name': name,
        'grades': kwargs.get('grades', []),
        'courses': kwargs.get('courses', []),
        'contact': kwargs.get('contact', '未提供')
    }
    print(f"学生姓名: {info['name']}")
    print(f"成绩: {info['grades']}")
    print(f"课程: {info['courses']}")
    print(f"联系方式: {info['contact']}")
    # 计算平均分
    if info['grades']:
        avg = sum(info['grades']) / len(info['grades'])
        print(f"平均分: {avg:.2f}")
# 使用示例
student_info("张三", 
             grades=[85, 92, 78],
             courses=["数学", "英语", "物理"],
             contact="zhangsan@email.com")
print("\n" + "="*30 + "\n")
student_info("李四",
             grades=[90, 88],
             courses=["化学"])

模拟打印机功能

def printer(*items, **settings):
    """
    模拟打印机,可以打印任意数量的内容,并支持自定义设置
    """
    # 默认设置
    config = {
        'separator': ' ',      # 分隔符
        'end': '\n',           # 结束符
        'uppercase': False,    # 是否大写
        'prefix': ''           # 前缀
    }
    # 更新用户设置
    config.update(settings)
    # 处理打印内容
    processed_items = []
    for item in items:
        if config['uppercase']:
            item = str(item).upper()
        else:
            item = str(item)
        processed_items.append(config['prefix'] + item)
    # 打印输出
    output = config['separator'].join(processed_items)
    print(output, end=config['end'])
# 使用示例
print("=== 基本打印 ===")
printer("Hello", "World")
print("\n=== 带分隔符 ===")
printer("Hello", "World", "Python", separator="-")
print("\n=== 大写 + 前缀 ===")
printer("hello", "world", uppercase=True, prefix="**", separator=" | ")

组合使用:装饰器记录函数调用

import time
from functools import wraps
def log_calls(func):
    """
    装饰器:记录函数调用的参数和执行时间
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        # 记录参数
        args_str = ', '.join([str(arg) for arg in args])
        kwargs_str = ', '.join([f"{k}={v}" for k, v in kwargs.items()])
        if args_str and kwargs_str:
            params = f"{args_str}, {kwargs_str}"
        else:
            params = args_str or kwargs_str
        print(f"调用函数: {func.__name__}({params})")
        # 执行函数
        result = func(*args, **kwargs)
        # 记录执行时间
        end_time = time.time()
        execution_time = end_time - start_time
        print(f"执行时间: {execution_time:.4f}秒")
        print(f"返回值: {result}")
        print("-" * 40)
        return result
    return wrapper
@log_calls
def calculate_sum(*numbers):
    """计算数字和"""
    time.sleep(0.1)  # 模拟耗时操作
    return sum(numbers)
@log_calls
def user_info(name, age, **extra_info):
    """用户信息"""
    info = f"用户: {name}, 年龄: {age}"
    if extra_info:
        info += f", 额外信息: {extra_info}"
    return info
# 使用示例
calculate_sum(1, 2, 3, 4, 5)
calculate_sum(10, 20, 30)
user_info("小明", 25, city="北京", job="工程师")
user_info("小红", 22)

灵活性案例:数据处理函数

def data_processor(*args, operation='sum', **options):
    """
    灵活的数据处理函数
    """
    if not args:
        return None
    # 基本操作
    if operation == 'sum':
        result = sum(args)
    elif operation == 'average':
        result = sum(args) / len(args)
    elif operation == 'max':
        result = max(args)
    elif operation == 'min':
        result = min(args)
    else:
        result = args
    # 应用额外选项
    if options.get('round_results', False):
        decimal_places = options.get('decimal_places', 2)
        result = round(result, decimal_places)
    if options.get('format_output', False):
        prefix = options.get('prefix', 'Result: ')
        return f"{prefix}{result}"
    return result
# 使用示例
print("=== 不同操作 ===")
print(data_processor(1, 2, 3, 4, 5))                    # 求和
print(data_processor(1, 2, 3, 4, 5, operation='average'))  # 平均值
print(data_processor(1, 2, 3, 4, 5, operation='max'))      # 最大值
print("\n=== 带选项 ===")
print(data_processor(10.123, 20.456, 30.789, 
                     operation='average',
                     round_results=True, 
                     decimal_places=1))
print(data_processor(1, 2, 3, operation='sum',
                     format_output=True,
                     prefix='计算结果: '))

实际项目案例:API请求构建器

def api_request_builder(endpoint, **params):
    """
    构建API请求,自动处理各种参数
    """
    base_url = "https://api.example.com"
    # 处理参数
    query_params = []
    for key, value in params.items():
        if value is not None:  # 忽略None值
            query_params.append(f"{key}={value}")
    # 构建URL
    if query_params:
        url = f"{base_url}/{endpoint}?{'&'.join(query_params)}"
    else:
        url = f"{base_url}/{endpoint}"
    return url
# 使用示例
print(api_request_builder("users", page=1, limit=10, sort="name"))
print(api_request_builder("users", user_id=123))
print(api_request_builder("search", q="Python", category="programming", 
                          sort="relevance", limit=20, page=1, 
                          lang="zh_CN"))
# 构建复杂查询
search_params = {
    'q': '机器学习',
    'filters': 'free',
    'duration': 'long',
    'sort': 'newest'
}
print(api_request_builder("courses", **search_params))
  1. *args` (位置参数打包)**:

    • 接收任意数量的位置参数
    • 在函数内部作为元组使用
    • 适合处理数量不定的参数列表
  2. kwargs` (关键字参数打包)**:

    • 接收任意数量的关键字参数
    • 在函数内部作为字典使用
    • 适合处理配置信息、可选参数
  3. 组合使用

    • 可以同时使用 *args**kwargs
    • 提供了最大的灵活性
  4. 实际应用场景

    • 装饰器
    • API接口
    • 配置系统
    • 数据处理
    • 日志记录

这些案例展示了不定长参数在实际项目中的灵活应用,让你的代码更加通用和可扩展。

抱歉,评论功能暂时关闭!