
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来文章
“刘心向学(53):*args 与 **kwargs —— 编写灵活函数的秘诀”
欢迎您的访问。
Share interest, spread happiness,
Increase knowledge, leave a beautiful!
Dear, this is LearningYard Academy.
Today, the editor brings you an article.
“Liu Xin Xiang Xue (53): *args and **kwargs — The Secret to Writing Flexible Functions”
Welcome to your visit.
一、思维导图(Mind Map)

二、引言(Introduction)
在软件开发中,一个永恒的挑战是:如何在确定性与灵活性之间取得平衡?
In software development, one eternal challenge is: how to strike a balance between determinism and flexibility?
函数接口尤其如此——参数太少,功能受限;参数太多,调用复杂。而现实需求又常常变化:今天只需两个参数,明天可能要支持十个。
Function interfaces are especially tricky — too few parameters limit functionality; too many make calls cumbersome. And real-world requirements often change: today you might need two parameters, tomorrow ten.
Python 为此提供了优雅的答案:
Python offers an elegant solution for this:
args 和 kwargs
它们不是魔法咒语,而是语言对“可扩展设计”的深刻支持。从标准库到主流框架(如 Django、Flask、PyTorch),你都能看到它们的身影。
They are not magic incantations but profound language support for “scalable design.” From standard libraries to major frameworks (like Django, Flask, PyTorch), you'll find them everywhere.
掌握它们,你就掌握了编写通用、可组合、向前兼容代码的关键。
Mastering them equips you with the key to writing generic, composable, forward-compatible code.
三、基本概念(Core Concepts)
args
:收集多余的位置参数,形成元组
: Collects extra positional arguments into a tuple
kwargs
:收集多余的关键字参数,形成字典
: Collects extra keyword arguments into a dictionary
Python编辑1defdemo(*args,**kwargs):
2print("args =", args)
3print("kwargs =", kwargs)
4
5demo(1,2, name="Alice", age=30)
6# args = (1, 2)
7# kwargs = {'name': 'Alice', 'age': 30}
args 和 kwargs 只是命名习惯,真正起作用的是 * 和 **
args and kwargs are just naming conventions; it's the * and ** that do the work.
四、典型应用场景(Typical Use Cases)
1. 可变参数函数
Variable Argument Functions
Python编辑1defaverage(*numbers):
2returnsum(numbers)/len(numbers)if numbers else0
2. 装饰器中透传参数
Argument Passing in Decorators
Python编辑1deftimer(func):
2defwrapper(*args,**kwargs):
3 start = time.time()
4 result = func(*args,**kwargs)
5print(f"{func.__name__} took {time.time()- start:.2f}s")
6return result
7return wrapper
3. 子类初始化
Child Class Initialization
Python编辑1classAnimal:
2def__init__(self, species):
3 self.species = species
4
5classDog(Animal):
6def__init__(self, name,*args,**kwargs):
7super().__init__(*args,**kwargs)
8 self.name = name
4. 解包传参(反向使用)
Unpacking Arguments (Reverse Usage)
Python编辑1data =[1,2,3]
2options ={"sep":" | ","end":"
"}
3print(*data,**options)# 输出: 1 | 2 | 3
五、注意事项(Caveats)
参数顺序必须严格遵守:
def func(pos, *args, kw_only, **kwargs)
Parameter order must be strictly followed:
def func(pos, *args, kw_only, **kwargs)
避免过度使用:如果参数含义明确,应显式声明
Avoid overuse: If parameter meanings are clear, declare them explicitly
调试时可通过 print(args, kwargs) 快速定位问题
For debugging, use print(args, kwargs) to quickly identify issues
六、结语(Conclusion)
*args 和 **kwargs 是 Python 对“开放封闭原则”的温柔实践——对扩展开放,对修改封闭。
*args and **kwargs embody Python’s gentle practice of the Open/Closed Principle — open for extension, closed for modification.
它们不是让你写出模糊不清的接口,而是赋予你在必要时保持弹性的能力。
They don't encourage writing ambiguous interfaces but rather provide the ability to remain flexible when necessary.
正如一位老程序员所说:
As an experienced programmer once said:
“好的 API 不是能接受一切,而是知道何时该说‘不’,又何时该说‘来吧’。”
“A good API doesn’t accept everything; it knows when to say ‘no’ and when to say ‘come on.’”
而 *args 与 **kwargs,正是那句恰到好处的“来吧”。
And *args and **kwargs are that perfect “come on.”
今天的分享就到这里了。
如果您对文章有独特的想法,
欢迎给我们留言,
让我们相约明天。
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
参考资料:通义千问
参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.
Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.
本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!
LearningYard新学苑
文字:song
排版:song
审核|qiu
















暂无评论内容