美文网首页
python中的*args和**kwargs

python中的*args和**kwargs

作者: thelong的学习日记 | 来源:发表于2020-05-16 20:25 被阅读0次

    通过小例子介绍args和*kwargs的功能

    example1
    def test(a,*args):
        print(a)
        print(args)
    
    test(1,2,3,4)
    ------------------------------------
    1
    (2, 3, 4)
    
    example2
    def test(a,*args,**kwargs):
        print(a)
        print(args)
        print(kwargs)
    
    test(1,2,3,4)
    ------------------------------------
    1
    (2, 3, 4)
    {}
    
    example3
    def test(a,*args,**kwargs):
        print(a)
        print(args)
        print(kwargs)
    
    test(1,2,3,4,b=10, c=6, d=7)
    ------------------------------------
    1
    (2, 3, 4)
    {'b': 10, 'c': 6, 'd': 7}
    

    kwargs.get(arg1,value):用于得到kwargs中arg1的值,如果kwargs未给出该值,那就得到value

    example4
    def test(a,*args,**kwargs):
        print(a)
        print(args)
        print(kwargs)
        x=kwargs.get('b',100)
        print(x)
    test(1,2,3,4,b=5, c=6, d=7)
    ------------------------------------
    1
    (2, 3, 4)
    {'b': 5, 'c': 6, 'd': 7}
    5
    
    example5
    def test(a,*args,**kwargs):
        print(a)
        print(args)
        print(kwargs)
        x=kwargs.get('e',100)
        print(x)
    test(1,2,3,4,b=5, c=6, d=7)
    ------------------------------------
    1
    (2, 3, 4)
    {'b': 10, 'c': 6, 'd': 7}
    100
    

    相关文章

      网友评论

          本文标题:python中的*args和**kwargs

          本文链接:https://www.haomeiwen.com/subject/ngirohtx.html