zoukankan      html  css  js  c++  java
  • python中的*args 和**kwargs

    *args是可变长参数,在函数内部以tuple形式存储;

    def fun_var_args(farg, *args):
        print "arg:", farg
        print(type(args))

    >>> fun_var_args(1, 'two', 3)
    arg: 1
    <type 'tuple'>

    def fun_var_args(farg, *args): 
        print "arg:", farg 
        for value in args: 
            print "another arg:", value 

    >>>fun_var_args(1, "two",3)

    arg: 1
    another arg: two
    another arg: 3

    对于参数**kwargs,输入时要指定key和value

    def fun_var_kwargs(farg, **kwargs): 
        print "arg:", farg 
        for key in kwargs: 
            print "another keyword arg: %s: %s" % (key, kwargs[key])

    >>>fun_var_kwargs(farg=1, myarg2='two', myarg3=3)

    arg: 1
    another keyword arg: myarg2: two
    another keyword arg: myarg3: 3

    参数kwargs在函数内部存储为dict:

    def fun_var_kwargs(farg, **kwargs): 
        print "arg:", farg 
        print(type(kwargs))

    >>>fun_var_kwargs(farg=1, myarg2='two', myarg3=3)
    arg: 1
    <type 'dict'>

  • 相关阅读:
    python之基础2
    python之文件2
    python之入门2
    python之入门
    python之多并发2
    python之面向对象2
    python之MySQL系列
    python之文件
    python之多并发
    Google身份验证器详解
  • 原文地址:https://www.cnblogs.com/HITSZ/p/9172931.html
Copyright © 2011-2022 走看看