*args and **kwargs in python explained

转载自:
https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/
例子:

first with *args

args = ("two", 3,5)
test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5

now with **kwargs:

kwargs = {"arg3": 3, "arg2": "two","arg1":5}
test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3

另外的例子:

*self._args 表示接受元组类参数;
*kwargs 表示接受字典类参数;
以下是网上的例子:
def foo(
args, **kwargs):
print 'args = ', args
print 'kwargs = ', kwargs
print '---------------------------------------'
if name == 'main':
foo(1,2,3,4)
foo(a=1,b=2,c=3)
foo(1,2,3,4, a=1,b=2,c=3)
foo('a', 1, None, a=1, b='2', c=3)
输出结果如下:
args = (1, 2, 3, 4)
kwargs = {}


args = ()
kwargs = {'a': 1, 'c': 3, 'b': 2}


args = (1, 2, 3, 4)
kwargs = {'a': 1, 'c': 3, 'b': 2}


args = ('a', 1, None)
kwargs = {'a': 1, 'c': 3, 'b': '2'}


————————————————
版权声明:本文为CSDN博主「绿竹痕」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jobjava/java/article/details/25062335

你可能感兴趣的:(*args and **kwargs in python explained)