Python函数可变参数args及kwargs释义
[wo@hai yz_test]$ more test_args.py
def foo(*args,**kwargs):
print 'args=',args,"len:",len(args)
print 'kwargs=',kwargs,"len:",len(kwargs)
print '**********************'
if __name__=='__main__':
foo(1,2,3)
foo(a=1,b=2,c=3)
foo(1,2,3,a=1,b=2,c=3)
foo(1,'b','c',a=1,b='b',c='c')
执行结果如下:
[wo@hai yz_test]$ python test_args.py
args= (1, 2, 3)
kwargs= {}
**********************
args= ()
kwargs= {'a': 1, 'c': 3, 'b': 2}
**********************
args= (1, 2, 3)
kwargs= {'a': 1, 'c': 3, 'b': 2}
**********************
args= (1, 'b', 'c')
kwargs= {'a': 1, 'c': 'c', 'b': 'b'}
**********************
def funcE(a, b, c):
print a
print b
print c
调用funcE(100, 99, 98)和调用funcE(100, c=98, b=99)的结果是一样的。
def funcF(a, **b):
print a
for x in b:
print x + ": " + str(b[x])
调用funcF(100, c='你好', b=200),执行结果
100
c: 你好
b: 200
可以看到,b是一个dict对象实例,它接受了关键字参数b和c。
def test_args(first, *args):
print 'Required argument: ', first
for v in args:
print 'Optional argument: ', v
test_args(1, 2, 3, 4)
[wo@hai yz_test]$ python 11_test.py
Required argument: 1
Optional argument: 2
Optional argument: 3
Optional argument: 4
def test_kwargs(first, *args, **kwargs):
print 'Required argument: ', first
for v in args:
print 'Optional argument (*args): ', v
for k, v in kwargs.items():
print 'Optional argument %s (*kwargs): %s' % (k, v)
test_kwargs(1, 2, 3, 4, k1=5, k2=6)
[wo@hai yz_test]$ python 11_test.py
Required argument: 1
Optional argument (*args): 2
Optional argument k2 (*kwargs): 6
Optional argument k1 (*kwargs): 5
Optional argument (*args): 3
Optional argument k2 (*kwargs): 6
Optional argument k1 (*kwargs): 5
Optional argument (*args): 4
Optional argument k2 (*kwargs): 6
Optional argument k1 (*kwargs): 5
# Use *args
def test_args(args):
print args
print type(args)
for e in args:
print e
args = [1, 2, 3, 4, 5]
test_args(*args)
[wo@hai yz_test]$ python 11_test.py
Traceback (most recent call last):
File "11_test.py", line 7, in
test_args(*args)
TypeError: test_args() takes exactly 1 argument (5 given)
改成如下格式:
def test_args(*args):
print args
print type(args)
for e in args:
print e
args = [1, 2, 3, 4, 5]
test_args(*args)
[wo@hai yz_test]$ python 11_test.py
(1, 2, 3, 4, 5)
1
2
3
4
5
# Use **kwargs
def test_args(*args):
print args
print type(args)
for e in args:
print e, args[e]
[wo@hai yz_test]$ python 11_test.py
Traceback (most recent call last):
File "11_test.py", line 16, in
test_args(**kwargs)
TypeError: test_args() got an unexpected keyword argument 'second'
改成如下形式:
[wo@hai yz_test]$ more 11_test.py
def test_args(**args):
print args
print type(args)
for e in args:
print e, args[e]
# Use **kwargs
kwargs = {
'first': 1,
'second': 2,
'third': 3,
'fourth': 4,
'fifth': 5
}
test_args(**kwargs)
[wo@hai yz_test]$ python 11_test.py
{'third': 3, 'second': 2, 'fourth': 4, 'fifth': 5, 'first': 1}
third 3
second 2
fourth 4
fifth 5
first 1