Python *args & **kwargs

*args

* Args variable is a list of positional arguments

* Args: packaged into a parameter tuple (tuple) function call to the

args call with function

def test1(*args):
    print(args)
    print(*args)
    test2(args)
    test2(*args)


def test2(*args):
    print(args)


if __name__ == '__main__':
    test1('a', 'b', 'c')

Output

('a', 'b', 'c')
a b c
(('a', 'b', 'c'),)
('a', 'b', 'c')

So *argsthree strings: 'a', 'b' , 'c'
argsis filled with a string of three tuples :( 'a', 'b' , 'c')

** kwargs

** kwargs variable keyword arguments list
** kwargs: The parameters packed into a dictionary (dict) function call to
the call by the function kwargs
Example:

def test1(**kwargs):
    print(kwargs)
    test2(kwargs=kwargs)
    test2(**kwargs)


def test2(**kwargs):
    print(kwargs)


if __name__ == '__main__':
    test1(a='a', b='b', c='c')

Output

{'a': 'a', 'b': 'b', 'c': 'c'}
{'kwargs': {'a': 'a', 'b': 'b', 'c': 'c'}}
{'a': 'a', 'b': 'b', 'c': 'c'}

So **kwargs= {a = 'a', b = 'b', c = 'c'}
Note that **kwargs does not directly printout
kwargs= { 'a': 'a ', 'b': 'b', 'c': 'c '}

to sum up

When the internal function calls to other * args or ** kwargs as a parameter function, passing the parameters should be * args or ** kwargs or kwargs instead args
parameter arg, * args, ** kwargs position three parameters must be It is certain. It must be (arg, * args, ** kwargs ) in this order, otherwise the program will complain

Guess you like

Origin www.cnblogs.com/dbf-/p/11606188.html