python 基础——*args和**kwargs

*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个dict。

def func(one, *args, **kwargs):
    print type(one)
    print type(args)
    print type(kwargs)
    print one
    print args
    print kwargs
    
func('hello', 1, 2, name='Bob', age='10')
func(1, 1, 2, name='Bob', age='10')
#输出
'''
<type 'str'>
<type 'tuple'>
<type 'dict'>
hello
(1, 2)
{'age': '10', 'name': 'Bob'}
<type 'int'>
<type 'tuple'>
<type 'dict'>
1
(1, 2)
{'age': '10', 'name': 'Bob'}
'''

注意:同时使用*args和**kwargs时,必须普通参数在最前面,*args参数列要在**kwargs前,像foo(a=1, b='2', c=3, a', 1, None, )这样调用的话,会提示语法错误“SyntaxError: non-keyword arg after keyword arg”

def func(*args, one, **kwargs):
    print type(one)
    print type(args)
    print type(kwargs)
    print one
    print args
    print kwargs

#输出
'''
语法错误!
File "<string>", line 1
    def func(*args, one, **kwargs):
                      ^
SyntaxError: invalid syntax

'''

借助 **kwargs 的特性,可以用此来创建字典

def kw_dict(**kwargs):
    return kwargs
print kw_dict(a=1,b=2,c=3)
#输出
'''
{'a': 1, 'c': 3, 'b': 2}
'''

 

posted @ 2016-08-13 14:49  弋痕夕的残影  阅读(371)  评论(0编辑  收藏  举报