不定长数目参数,*args, **kwargs
*args
当函数参数数目不确定时,‘*’将一组位置参数打包成一个参数值容器。
1 2 3 4 5 6 7 8 9 10 11 12 13 | def demo(a, * args): print ( 'a:' , a) print ( 'args:' , args) print ( 'type of args:' , type (args)) print ( 'length of args:' , len (args)) demo( 1 , 2 , 'hello' , []) # 运行结果: # a: 1 # args: (2, 'hello', []) # type of args: <class 'tuple'> # length of args: 3 |
我们可以把程序中的*args改为*x、*b等等任意的名字,但是Python官方建议使用*args,这样其他人一看就知道这在干嘛。
若*args不是在最后,则需要在参数传入时,需用关键字参数传入*args后面的参数名:
1 2 3 4 5 6 7 8 9 10 11 12 13 | def demo( * args, a): print ( 'a:' , a) print ( 'args:' , args) print ( 'type of args:' , type (args)) print ( 'length of args:' , len (args)) demo( 1 , 2 , 'hello' , [], a = 3 ) # 运行结果: # a: 3 # args: (1, 2, 'hello', []) # type of args: <class 'tuple'> # length of args: 4 |
**kwargs
**可以将参数收集到一个字典中,参数的名字是字典的键,对应参数的值是字典的值。
1 2 3 4 5 6 7 8 9 10 11 | def demo(a, * * kwargs): print ( 'a:' , a) print ( 'kwargs:' , kwargs) print ( 'type of kwargs:' , type (kwargs)) demo( 0 , x1 = 1 , x2 = 2 , x3 = 3 ) # 运行结果: # a: 0 # kwargs: {'x1': 1, 'x2': 2, 'x3': 3} # type of kwargs: <class 'dict'> |
*args和**kwargs组合使用
1 2 3 4 5 6 7 8 9 10 11 | def demo(a, * args, * * kwargs): print ( 'a:' , a) print ( 'args:' , args) print ( 'kwargs:' , kwargs) demo( 0 , 8 , 9 , x1 = 1 , x2 = 2 , x3 = 3 ) # 运行结果: # a: 0 # args: (8, 9) # kwargs: {'x1': 1, 'x2': 2, 'x3': 3} |
在函数调用中使用*和**
*和**不仅可以在函数定义中使用,还可以在函数调用中使用。在调用时使用就相当于pack(打包)和unpack(解包)。
1 2 3 4 5 6 7 8 | def demo(a, b, c): print ( 'a:{}, b:{}, c:{}' . format (a, b, c)) lst = [ 1 , 2 , 3 ] demo( * lst) # 运行结果: # a:1, b:2, c:3 |
更简单的一个示例是关于print函数的:
1 2 3 4 5 | lst = [ 1 , 2 , 3 ] print ( * lst) # 运行结果: # a:1, b:2, c:3 |
最后举一个‘**’的例子
1 2 3 4 5 6 7 8 | def demo(a, b, c): print ( 'a:{}, b:{}, c:{}' . format (a, b, c)) score = { 'a' : 90 , 'b' : 85 , 'c' : 76 } demo( * * score) # 运行结果: # a:90, b:85, c:76 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码