Hi, boys. I find it difficult for Python novices to understand the two magical variables of *args and **kwargs. What the hell are they? First of all, I first tell you the fact that it is not necessary to write *args and **kwargs completely, we can only write * and * *. You can also write *var and **vars. Writing *args and **kwargs is just a habit that everyone abides by. Now let's start with the *args.
Use of *args
*args and **kwargs are usually used in function definitions. *args and **kwargs allow you to pass an indefinite number of arguments to the function. "Do not quantify" means that you do not know when you define a function that the caller will pass several parameters in. *args is able to receive non-quantitative keyword parameters. Here's an example to illustrate this point
This example produces the following result
This should be explained more clearly, and then we say the Ming **kwargs
Use of **kwargs
**kwargs allows you to pass non-quantitative keyword arguments. If you need to define a non-quantitative named parameter in a function, then you will have to use **kwargs. Here's an example to illustrate this usage:
In this example we deal with some of the keyword parameters. This is the basic use of **kwargs, you can see that **kwargs is very useful. Next, let's illustrate the use of *args and **kwargs to pass a "parameter to a list", or "parameter of a dictionary" to a function when calling a function.
use *args and **kwargs to invoke a function
Here we describe how to use *args and **kwargs to invoke a function, assuming you have such a function.
Here we use *args and **kwargs to pass parameters to this function, which we can do:
Order of use of *args and **kwargs and common parameters
If you want to use these three parameters at the same time, the order between them is
So far, the usage of *args and **kwargs is done, and I hope it helps.
Disclaimer: This article is from a Python programmer, translated by the Python tribe
The role of *arg and **kwargs in Python