Usage of *args and **kwargs to pass variable-length parameters in Python functions

Reference from: http://www.jb51.net/article/78705.htm 

 

The single asterisk form (*args) is used to pass unnamed key variadic argument lists. The double asterisk form (**kwargs) is used to pass a list of key-valued varargs.

1. A fixed position parameter and two variable length parameters are passed.

def test_var_args(farg, *args):
  print "formal arg:", farg
  for arg in args:
    print "another arg:", arg
 
test_var_args(1, "two", 3)

turn out:

formal arg: 1
another arg: two
another arg: 3

 

2. One fixed parameter and two key-value parameters.

def test_var_kwargs(farg, **kwargs):
  print "formal arg:", farg
  for key in kwargs:
    print "another keyword arg: %s: %s" % (key, kwargs[key])
 
test_var_kwargs(farg=1, myarg2="two", myarg3=3)

turn out:

formal arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3

 

3. When calling a function, use *args and **kwargs

 

def test_var_args_call(arg1, arg2, arg3):
  print "arg1:", arg1
  print "arg2:", arg2
  print "arg3:", arg3
 
args = ("two", 3)
test_var_args_call(1, *args)

turn out:

arg1: 1
arg2: two
arg3: 3

-------------------------------------------

Key-value pair method:

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

 
kwargs = {"arg3": 3, "arg2": "two"}
test_var_args_call(1, **kwargs)

 turn out:

arg1: 1
arg2: two
arg3: 3

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325166413&siteId=291194637