Python is the simplest way to support mutable parameters, such as using default parameters, such as:
def test_defargs(one, two = 2): print ‘Required argument: ‘, one print ‘Optional argument: ‘, twotest_defargs(1)# result:# Required argument: 1# Optional argument: 2test_defargs(1, 3)# result:# Required argument: 1# Optional argument: 3
Of course, the topic in this article is not about default parameters, but another way to achieve variable parameters (Variable Argument): Using *args and **kwargs syntax. Where *args is a mutable list of positional arguments, **kwargs is a variable keyword arguments list. Also, *args must precede **kwargs, because positional arguments must precede keyword arguments.
The basic usage of both is introduced first.
The following example uses *args and contains a required parameter:
def test_args(first, *args): print ‘Required argument: ‘, first for v in args: print ‘Optional argument: ‘, vtest_args(1, 2, 3, 4)# result:# Required argument: 1# Optional argument: 2# Optional argument: 3# Optional argument: 4下面一个例子使用*kwargs, 同时包含一个必须的参数和*args列表:def test_kwargs(first, *args, **kwargs): print ‘Required argument: ‘, first for v in args: print ‘Optional argument (*args): ‘, v for k, v in kwargs.items(): print ‘Optional argument %s (*kwargs): %s‘ % (k, v)test_kwargs(1, 2, 3, 4, k1=5, k2=6)# results:# Required argument: 1# Optional argument (*args): 2# Optional argument (*args): 3# Optional argument (*args): 4# Optional argument k2 (*kwargs): 6# Optional argument k1 (*kwargs): 5
The *args and **kwargs grammars can be used not only in function definitions, but also in function calls. The difference is that if you use *args and **kwargs at the location where the function is defined is a process that takes the parameter pack, then it is a procedure to unpack the parameters when the function is called. The following example is used to deepen understanding:
def test_args(first, second, third, fourth, fifth): print ‘First argument: ‘, first print ‘Second argument: ‘, second print ‘Third argument: ‘, third print ‘Fourth argument: ‘, fourth print ‘Fifth argument: ‘, fifth# Use *argsargs = [1, 2, 3, 4, 5]test_args(*args)# results:# First argument: 1# Second argument: 2# Third argument: 3# Fourth argument: 4# Fifth argument: 5# Use **kwargskwargs = { ‘first‘: 1, ‘second‘: 2, ‘third‘: 3, ‘fourth‘: 4, ‘fifth‘: 5}test_args(**kwargs)# results:# First argument: 1# Second argument: 2# Third argument: 3# Fourth argument: 4# Fifth argument: 5
Functions can be easily defined using *args and **kwargs, and extensibility can be enhanced for future code maintenance.
Understanding *args and **kwargs in Python