How to use * args and * * kwargs in python
This article is about how to use * args and * * kwargs in python. I think it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.
1 * and * *
In fact, it does not have to be written as "* args and * * kwargs". The only thing that really works when passing parameters is the * (asterisk) in front of the variable. You can also write * params and * * kv_params.
* the parameters passed in will be stored as tuples, which is a tuple.
* * before being used for parameters, it means that the passed parameters will be stored in the form of a dictionary, which is a dictionary.
Next, we will introduce exactly how they are used in the form of code!
"Talk is cheap,Show you the code"
2 * usage of args
* args and * * kwargs are mainly used when defining functions. * args is used to send a variable number of argument lists of non-key-value pairs to a function.
The execution result of the above code is as follows:
* args: ('java',' c _ args, 'go') type: parameter passed through * args: parameter passed by java via * args: parameter passed by * args + parameter passed through * args: go
Usage of 3 * * kwargs
* * kwargs allows you to pass indefinite length key-value pairs as arguments to a function. If you want to handle some named parameters in a function, you have to use * kwargs. Here is an example:
Def test_kwargs (* * kwargs): print ("* * kwargs:", kwargs, "Type:", type (kwargs)) for key, value in kwargs.items (): print ("{0} = = {1}" .format (key, value)) test_kwargs (name= "tom", age= "3")
The execution result of the above code is as follows:
* * kwargs: {'name':' tom', 'age':' 3'} Type: name = = tomage = = 3
* * kwargs assembles several parameters into a dictionary and passes them to the test_kwargs function. Here, you can know how to handle a key-value pair parameter in a function.
4 use * args and * * kwargs to call functions
So now we will see how to use * args and * * kwargs to call a function. Suppose you have a function like this:
Def test_args_kwargs (arg1, arg2, arg3): print ("arg1:", arg1) print ("arg2:", arg2) print ("arg3:", arg3)
You can use * args or * * kwargs to pass parameters to this function:
# use * args method args = ("python", "java", "go") test_args_kwargs (* args) # use * * kwargs mode kwargs = {"arg2": "java", "arg3": "go", "arg1": "python"} test_args_kwargs (* * kwargs) above is how to use * args and * * kwargs in python The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.