2021-11-30,这是我写的第一篇博客,以前总想着用笔和纸进行记录,但是现在想改变一下想法,那就从现在开始。
因为经常遇见*args,**kwargs,但是每次遇见都要去百度一下,也挺麻烦的,所以随手记录一下笔记。
1、*args,**kwargs是Python中的可变参数,在编写程序函数或者类函数,发现参数不确定的时 候,可以使用*args,**kwargs;
2、*args是一个接收无名参数,返回一个tuple(元组);
例子1:
def func(*args):
print(args)
func(1,2,3,4) # 运行结果(1, 2, 3, 4)
func([1,2,3], (4,5,6), {"key":"hello"}) # 运行结果([1, 2, 3], (4, 5, 6), {'key': 'hello'})
func("hello", 1,2,3) # 运行结果('hello', 1, 2, 3)
例子2:
def func(x, y, *args):
"""
如果存在已知参数,传入的参数怎么分配
"""
print(args)
func(1,2,3,4) # 运行结果(3, 4)
func([1,2,3], (4,5,6), {"key":"hello"}) # 运行结果({'key': 'hello'})
func("hello", 1,2,3) # 运行结果(2, 3)
会按照顺序,将参数从左到右分配,剩下的归于*args。
3、**kwargs被称为关键字参数,返回一个dict(字典)。
例子1:必须得传入key=value格式的参数,否则会报错
def func(**kwargs):
print(kwargs)
func(1,2,3,4) # 运行结果:TypeError: func() takes 0 positional arguments but 4 were given
func({"key":"python"}) # TypeError: func() takes 0 positional arguments but 1 was given
func(key="hello", value="python") # 运行结果:{'key': 'hello', 'value': 'python'}
例子2:
def func(x, **kwargs):
"""
如果存在已知参数,传入的参数怎么分配
"""
print(x, end=" ")
print(kwargs)
func(key="hello", value="python") # 运行结果:TypeError: func() missing 1 required positional argument: 'x'
func(x=10, key="hello") # 运行结果:10 {'key': 'hello'}
func([1,2], key="hello") # 运行结果:[1, 2] {'key': 'hello'}
结合使用
例子1:
def func(*args, **kwargs):
print(args, end=" ")
print(kwargs)
func(key="hello", value="python") # 运行结果:() {'key': 'hello', 'value': 'python'}
func(10, "hello", key="hello") # 运行结果:(10, 'hello') {'key': 'hello'}
例子2:
def func(x, *args, **kwargs):
"""
当存在已知参数x的时候,必须按照x的类型,保证有一个能传参给x,顺序也得一致
"""
print(x, end=" ")
print(args, end=" ")
print(kwargs)
func(key="hello", value="python") # 运行结果:TypeError: func() missing 1 required positional argument: 'x'
func(10, "hello", key="hello") # 运行结果:10 ('hello',) {'key': 'hello'}
注意点:
1、使用未知参数的时候, 普通参数放于*args,如果不这样放,则在使用该函数的时候需要指明
给该普通参数传递的是什么值;
def func(*args, x, **kwargs):
print(x, end=" ")
print(args, end=" ")
print(kwargs)
func(10, x="hello", key="hello") # 运行结果:hello (10,) {'key': 'hello'}
2、*args必须放在**kwargs的前面,否则无法编译通过。
建议命名规则为:def func(普通参数名1,普通参数名2......,*args,**kwargs )