首页 > 编程语言 > 详细

python 基础——*args和**kwargs

时间:2016-08-13 15:30:07      阅读:242      评论:0      收藏:0      [点我收藏+]

*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}
‘‘‘

 

python 基础——*args和**kwargs

原文:http://www.cnblogs.com/licongyu/p/5767989.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!