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:

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.

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

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,

args = (1,2,3)
func(1,2,3)

you will also get the same output
1
2
3

Analog to **kwargs

func(name = "pangpang", age = "12", hobby = "sleeping")

you will get the output:

hobby sleeping
age 12
name pangpang

This is equivalent to

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.