zoukankan      html  css  js  c++  java
  • python函数可变参数*args和**kwargs区别

    #*args(元组列表)和**kwargs(字典)的区别

    def tuple_test(*args):
        for i in args:
            print 'hello'+i
    s=('xuexi','mili')
    tuple_test(*s)

    结果

    helloxuexi
    hellomili

    def dict_test(**kwargs):
        for i in kwargs:
            print i,kwargs[i]
    ss={'name':'xuexi',"nick":'0000'}        
    dict_test(**ss)

    结果:

    nick 0000
    name xuexi

    3,可变参数和关键字参数

    def func(*args, **kwargs):
        return sum(args) + sum(kwargs.values())
    args = [1, 2]
    kwargs = {'a':3, 'b':4}
    func(*args, **kwargs) 
    # => 3+7  10
    args = []
    kwargs = {'a':3, 'b':4, 'c': 5}
    func(*args, **kwargs)
     # =>0+12  12

     https://blog.csdn.net/parameter_/article/details/78555470

    def foo(*args,**kwargs):
    print 'args is',args
    print 'kwargs is',kwargs
    foo(1,2)
    foo(k=1,w=2,a=3,r=4,g=5,s=6)
    foo(1,2,a=1,b=2,c=2)
    foo('a',1,None,a=1,b='2',c=3)

    结果

    args is (1, 2)
    kwargs is {}
    args is ()
    kwargs is {'a': 3, 'g': 5, 'k': 1, 's': 6, 'r': 4, 'w': 2}
    args is (1, 2)
    kwargs is {'a': 1, 'c': 2, 'b': 2}
    args is ('a', 1, None)
    kwargs is {'a': 1, 'c': 3, 'b': '2'}


  • 相关阅读:
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    Evanyou Blog 彩带
  • 原文地址:https://www.cnblogs.com/xueli/p/6168849.html
Copyright © 2011-2022 走看看