I was reading some stuff about *args and **kwargs in function definitions. They are used to pass a variable number of arguments to a function. The *args is used to pass a non-keyworded, variable-length argument list, and the double asterisk form is used to pass a keyworded, variable-length argument list. Here is an example of how to use the non-keyworded form. This example passes one formal (positional) argument, and two more variable length arguments.
def test_args(farg, *args):
print "farg:", farg
for arg in args:
print "other arg:", arg
test_args(1, "two", 3)
Results:
farg: 1
other arg: two
other arg: 3
Another example of how to use the keyworded form. Again, one formal argument and two keyworded variable arguments are passed.
def test_kwargs(farg, **kwargs):
print "farg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
test_kwargs(farg=1, myarg2="two", myarg3=3)
Results:
farg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3
This is helpful to me to build the python functions more clearly.
This is helpful ! Thanks.
RépondreSupprimer