*args and **kwargs are primarily used for function definitions. You can pass an indefinite number of arguments to a function. The indefinite meaning is: in advance do not know, the function user will pass the number of parameters to you, so in this scenario use these two keywords. In fact, it is not necessary to write *args and **kwargs. * (asterisk) is required. You can also write *ar and **k. and written *args and **kwargs is just a popular naming convention.
There are two ways that Python functions pass parameters:
positional parameters (positional argument)
keyword parameters (keyword argument)
The difference between *args and **kwargs, both of which are mutable parameters in Python.
*args represents any number of nameless parameters, which are essentially a tuple;
**kwargs represents a keyword parameter, which is essentially a dict;
If you use both *args and **kwargs, you must *args the parameter column before **kwargs.
Example 1.
def fun (*args,**kwargs):
Print (' args= ', args)
Print (' kwargs= ', Kwargs)
Fun (1,2,3,4,a= ' A ', b= ' B ', c= ' C ', d= ' D ')
Output:
Args= (1, 2, 3, 4)
kwargs= {' A ': ' A ', ' B ': ' B ', ' C ': ' C ', ' d ': ' d '}
Example 2:
def mutil (Name,*ar):
Print (name, "Master, hello")
For item in AR:
Print ("My name is:", item)
Mutil ("Liuhu", "Xiaoyun", "Liuwei")
# Hello, Master Liuhu.
# My name is: Xiaoyun
# My name is: Liuwei
Example 3:
def Love (**kwargs):
For Key,value in Kwargs.items ():
Print ("{0} loves {1}". Format (Key,value))
Love (name= "Liuhu", age=18)
# name in love with Liuhu
# Age in love with 18
Example 4:
def test (arg1, Arg2, ARG3):
Print ("Arg1:", arg1)
Print ("Arg2:", arg2)
Print ("Arg3:", Arg3)
args = ("Both", 3, 5)
Test (*args)
Kwargs = {"Arg3": 3, "arg2": "A", "Arg1": 5}
Test (**kwargs)
# Arg1:two
# Arg2:3
# Arg3:5
# Arg1:5
# Arg2:two
# Arg3:3
The *args and **kwargs usage of Python3 advanced