*args and **kwargs in Python

Python里面*args和**kwargs的用途和c里面[ccib_c]**argv[/ccib_c]的用法类似,都是用来表示可变参数。[ccib_c]int main (int argc, char **argv)//Variable-length arguments in c[/ccib_c]

*args和**kwargs的区别在于前者用于表示非关键字可变长度参数,后者表示关键字可变长度参数。

*args

[ccb_python]
def func_args(arg1, *args):
print ‘Normal argument:’, arg1
for arg in args:
print ‘variable arg:’, arg

>>> func_args(1, 2, ‘3’)
Normal argument: 1
variable arg: 2
variable arg: 3
[/ccb_python]

**kwargs

[ccb_python]
def func_kwargs(arg1, **kwargs):
print ‘Normal argument:’, arg1
for key in kwargs:
print ‘Keyworded variable arg:’, key, kwargs[key]

>>> func_kwargs(arg1=1, karg1=’2′, karg2=3)
Normal argument: 1
Keyworded variable arg: karg2 3
Keyworded variable arg: karg1 2
[/ccb_python]

除了定义函数,*args和**kwargs还可以用来调用函数。

[ccb_python]
def func(arg1, arg2, arg3):
print ‘arg1:’, arg1
print ‘arg2:’, arg2
print ‘arg3:’, arg3

>>> args = (2, ‘3’)
>>> kwargs = {‘arg2’:2, ‘arg3′:’3’}
>>> func(1, *args)
arg1: 1
arg2: 2
arg3: 3
>>> func(1, **kwargs)
arg1: 1
arg2: 2
arg3: 3
[/ccb_python]

《*args and **kwargs in Python》有1个想法

发表评论

电子邮件地址不会被公开。 必填项已用*标注