In Python functions, you often see one or two asterisks before the input parameters, for example:
def foo(param1, *param2):
def bar(param1, **param2):
These two usages are actually both used to import any number of parameters into a Python function.

Single asterisk (*): *agrs

Imports all parameters in the form of a tuple:

Example

def foo(param1, *param2):
    print (param1)
    print (param2)
foo(1,2,3,4,5)

The output of the above code is:

1
(2, 3, 4, 5)

Double asterisks (**): **kwargs

Double asterisks (**) import parameters in the form of a dictionary:

Example

def bar(param1, **param2):
    print (param1)
    print (param2)
bar(1,a=2,b=3)

The output of the above code is:

1
{'a': 2, 'b': 3}

In addition, another usage of a single asterisk is to unpack an argument list:

Example

def foo(example_1, example_2):
    print(example_1, example_2)
l = [1, 2]
foo(*l)

The output of the above code is:

1 2
Of course, these two usages can appear in a function at the same time:

Example

def foo(a, b=10, *args, **kwargs):
    print (a)
    print (b)
    print (args)
    print (kwargs)
foo(1, 2, 3, 4, e=5, f=6, g=7)

The output of the above code is:

1
2
(3, 4)
{'e': 5, 'f': 6, 'g': 7}

Original URL: https://www.cnblogs.com/arkenstone/p/5695161.html