Python语法系列博客 · 第9期[特殊字符] 函数参数进阶:*args、**kwargs 与参数解包技巧
上一期小练习解答(第8期回顾)
✅ 练习1:整数转字符串列表
nums = [1, 2, 3, 4, 5]
str_list = list(map(str, nums))
✅ 练习2:筛选回文字符串
words = ["madam", "hello", "noon", "python"]
palindromes = list(filter(lambda x: x == x[::-1], words))
✅ 练习3:使用 reduce 计算乘积
from functools import reduce
product = reduce(lambda x, y: x * y, [2, 3, 4]) # 24
✅ 练习4:lambda 表达式计算 x² + 2x + 1
quad = lambda x: x**2 + 2*x + 1
result = quad(3) # 16
本期主题:函数参数进阶
🟦 9.1 位置参数、关键字参数复习
def greet(name, message="Hello"):print(f"{message}, {name}!")greet("Alice") # Hello, Alice!
greet("Bob", message="Hi") # Hi, Bob!
9.2 不定长参数:*args
和 **kwargs
✅ *args
:接收任意个数的位置参数,形式为元组。
def add_all(*args):return sum(args)print(add_all(1, 2, 3)) # 6
✅ **kwargs
:接收任意个数的关键字参数,形式为字典。
def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Alice", age=30)
9.3 混合使用:参数顺序规则
def func(a, b=2, *args, **kwargs):print(a, b, args, kwargs)func(1, 3, 4, 5, x=10, y=20)
# 输出:1 3 (4, 5) {'x': 10, 'y': 20}
✅ 推荐顺序:位置参数 → 默认参数 → *args → **kwargs
9.4 参数解包技巧
🔹 列表或元组解包
def multiply(x, y):return x * yargs = (3, 4)
print(multiply(*args)) # 12
🔹 字典解包
def introduce(name, age):print(f"My name is {name}, I'm {age} years old.")info = {"name": "Tom", "age": 25}
introduce(**info)
9.5 实用案例
📌 自动打印任意函数的参数内容(日志用途)
def debug_args(*args, **kwargs):print("位置参数:", args)print("关键字参数:", kwargs)debug_args(1, 2, name="Alice", age=30)
📌 合并多个字典
d1 = {"a": 1}
d2 = {"b": 2}
d3 = {**d1, **d2}
print(d3) # {'a': 1, 'b': 2}
本期小练习
-
编写一个函数
average(*args)
,计算传入任意多个数的平均值。 -
编写一个函数
build_profile(**kwargs)
,将所有键值对整理为一个字符串表示。 -
给定函数
def f(a, b, c):
,尝试使用元组和字典进行解包调用。 -
尝试使用
*args
实现不定长的字符串拼接函数。
本期小结
-
掌握了函数的高级参数使用方式:
*args
、**kwargs
。 -
学会了使用参数解包(和*)技巧。
-
能够组合参数来构建更灵活的函数接口。
第10期预告:
下一期将探索:
-
Python中的作用域与变量查找(LEGB原则)
-
局部变量、全局变量与
global
/nonlocal
的使用 -
闭包的概念与应用场景