Python中*args和**kwargs的博弈
*args用法
传递任意数量的参数
当你不确定你的函数里将要传递多少参数时你可以用*args
.例如,它可以传递任意数量的参数。
def print_everything(*args):
for count, thing in enumerate(args):
print '{0}. {1}'.format(count, thing)
...
'apple', 'banana', 'cabbage') print_everything(
0. apple
1. banana
2. cabbage
在函数处新增x和y变量
在函数中如果定义了变量x和y,*args放在函数中可以新增x和y的变量,简答方便。
def func(x,y,*args):
print(type(x))
print(x)
print(y)
print(type(args))
print(args)
print_func(1,2,'one',[])
>>>
<class 'int'>
1
2
<class 'tuple'>
('one', [])
将*args放在函数变量最前面
def func(*args,x,y):
print(type(x))
print(x)
print(y)
print(type(args))
print(args)
运行时出现如下报错信息:
TypeError: func() missing 2 required keyword-only arguments: 'x' and 'y'
def func(*args,x,y):
print(type(x))
print(x)
print(y)
print(type(args))
print(args)
print_func(1,2,'one',[],x='x',y='y')
可以正确输出
<class 'str'>
x
y
<class 'tuple'>
(1, 2, 'one', [])
**kwargs用法
**kwargs
允许你将不定长度的 【键值对 key-value 】,作为参数传递给一个函数。如果你想要在一个函数里处理带名字的参数,你应该使用**kwargs
**kwargs
允许你使用没有事先定义的参数名:
def table_things(**kwargs):
for name, value in kwargs.items():
print '{0} = {1}'.format(name, value)
...
'fruit', cabbage = 'vegetable') table_things(apple =
cabbage = vegetable
apple = fruit

组合使用 args
,*args
和 **kwargs
来调用函数
命名参数首先获得参数值然后所有的其他参数都传递给*args
和**kwargs
.命名参数在列表的最前端
def func(x, *args, **kwargs):
print(x)
print(args)
print(kwargs)
print_func(1, 2, 3, 4, y=1, a=2, b=3, c=4)
运行结果
1
(2, 3, 4)
{'y': 1, 'a': 2, 'b': 3, 'c': 4}
推荐阅读
(点击标题可跳转阅读)
老铁,三连支持一下,好吗?↓↓↓

点分享
点点赞
点在看
评论