the asterik * in python
Asterik in python is usually very confused for the beginner. Some times it appears one time before a variable like *args, some times it appears two times like **args.
Usually it appears in function definition:
1 2 | def func( * args1, * * args2): pass |
* and ** allow arbitrary number of arguments. Here the *args is somehow like a tuple of arguments, **kwargs is like a dictionary of arguments.
1 2 3 4 5 | def func( * args, * * kwargs): for member in args: print member for member in kwargs: print member, "\t" , kwargs[member] |
let see the *args, call the function
1 | func( 1 , 2 , 3 ) |
you will get the output:
1
2
3
you can also call the function with *args, the type of args should be a tuple or a list, * means decompose the tuple or list,
1 2 | args = ( 1 , 2 , 3 ) func( 1 , 2 , 3 ) |
you will also get the same output
1
2
3
Analog to **kwargs
1 | func(name = "pangpang" , age = "12" , hobby = "sleeping" ) |
you will get the output:
hobby sleeping
age 12
name pangpang
This is equivalent to
1 2 | kwargs = { "name" : "pangpang" , "age" : "12" , "hobby" : "sleeping" } func( * * kwargs) |
you will get the same output like above.
I put the code in Gist, you can download and try it.
def func(*args, **kwargs): | |
for member in args: | |
print member | |
for member in kwargs: | |
print member,"\t", kwargs[member] | |
#call the function | |
func(1,2,3) | |
args = [1,2,3] | |
func(*args) | |
func(name = "pangpang", age = "12", hobby = "sleeping") | |
kwargs = {"name":"pangpang","age":"12", "hobby":"sleeping"} | |
func(**kwargs) | |