2013年10月14日星期一

Python *args and **kargs

关于*args和**kargs的区别和用法,这段代码足够解释一切了。*args是单个不定参数,**kargs是k-v的不定参数
def any_function(required_arg, *args, **kwargs):
    print required_arg
 
    # args will be a list of positional arguments
    # because it has * before it
    if args: # If there is anything in args
        print args
 
    # kwargs will be a dictionary of keyword arguments,
    # because it has ** before it
    if kwargs: # If there is anything in kwargs
        print kwargs
 
any_function("Required Argument.")
any_function("Required Argument", 1, 2, "pos3")
any_function("Required Argument", (1, 2), "pos3", keyword1=5, keyword2="spam")
输出:
Required Argument.
Required Argument
(1, 2, 'pos3')
Required Argument
((1, 2), 'pos3')
{'keyword2': 'spam', 'keyword1': 5}

没有评论:

发表评论