In Python functions, you often see one or two asterisks before the input parameters, for example: These two usages are actually both used to import any number of parameters into a Python function.
def foo(param1, *param2):
def bar(param1, **param2):
def bar(param1, **param2):
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)
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)
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)
print(example_1, example_2)
l = [1, 2]
foo(*l)
The output of the above code is:
1 2Of 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)
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