Link to the original text :Python Medium *args and **kwargs(python Based on learning )_ Dandelion dust blog -CSDN Blog _**kwargs
1、*args and **kwargs It is mainly used to define the variable parameters of a function
2、*args: Send a variable number of parameter lists of non key value pairs to the function
3、**kwargs: Send a variable number of parameter lists of key value pairs to the function
4、 If you want to use a named variable inside a function ( Like a dictionary ), So use **kwargs.
The purpose of defining variable parameters is to simplify the call .
* and ** The role here : Packing parameters .
1、*args and **kwargs Not fixed , Only the front * and ** Is fixed and immutable , The following name can be changed at will , for example *vals A variable number of parameters representing non key value pairs ,**parms Represents a variable number of key value pairs . Use *args and **kwargs, It's a custom of Convention , You can also not use this name .
2、 When used at the same time *args and **kwargs when ,*args Must be written in **kwargs Before .
def test_args(*args):
print(args)
def test_kwargs(**kwargs):
print(kwargs)
print(type(kwargs))
for key, value in kwargs.items():
print("{} == {}".format(key, value))
def test_all(*args,**kwargs):
print(args)
print(kwargs)
∗ Put function test_args() Multiple parameters received 'name','age','address','sex'
, Packed into Tuples ('name','age','address','sex')
, Assigned to the formal parameter args.
test_args('name','age','address','sex')
# ('name', 'age', 'address', 'sex')
** Put function test_kwargs() Multiple parameters received , With Dictionaries Is assigned to a formal parameter kwargs.
test_kwargs(name='zxf',age=23,address='zhejiang')
# {'name': 'zxf', 'age': 23, 'address': 'zhejiang'}
# <class 'dict'>
# name == zxf
# age == 23
# address == zhejiang
test_all('name','age',name='zxf',age=23)
# ('name', 'age')
# {'name': 'zxf', 'age': 23}