python中的*args和**kwargs

2020-05-16  本文已影响0人  thelong的学习日记

通过小例子介绍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
上一篇下一篇

猜你喜欢

热点阅读