*args, **kwargs in Python

We will find that *args and **kwargs appear in some python program functions. This means that an indefinite number of arguments can be passed to this function.

Indeterminate means you don't know how many arguments will be passed to this function, so use *args and **kwargs for this scenario.

*args use case:

The first parameter is a parameter that must be passed in, so the first formal parameter is used, and the latter three formal parameters are passed as actual parameters as a variable parameter list, and its type is a tuple.

def method1(arg, *args):
    print("first normal arg:", arg)
    print(type(args))
    for arg in args:
        print("another arg through *argv:", arg)

method1('aa', 'bb', 'cc', 'dd')

The first parameter is a parameter that must be passed in, so the first formal parameter is used, and the latter three formal parameters are passed as actual parameters as a variable parameter list, and its type is a tuple.

**kwargs use case:

**kwargs is to pass a dictionary of variable keyword parameters to function arguments, and the length of the parameter list can also be 0 or other values.

def method3(**kwargs):
    print(type(kwargs))
    print(kwargs)

method3(a=10, b=20, c='python', d=[])

From the running results, we can see that kwargs is presented in the form of a dictionary. fruit 

Let's look at another example of combining arg with *args and **kwargs. 

def method2(first, *args, **kwargs):
    print('first normal arg:', first)
    print(type(kwargs))
    for v in args:
        print('Optional argument(args):', v)
    for k, v in kwargs.items():
        print('Optional argument %s (kwargs): %s' % (k,v))

method2(1, 2, 3, 4, key_1=5, key_2=6)

The result of the operation is:

 We understand more clearly that when printing, kwargs presents the incoming parameters in the form of a dictionary.

 function call:

def test(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)

args = ("one", 2, 3)
test(*args)

kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test(**kwargs)

Guess you like

Origin blog.csdn.net/weixin_44516623/article/details/127041911