*args and **kwargs in python (python basic learning)
Article Directory
文章抄自
*args and **kwargs in Python (Python Basic Learning) - CSDN - Dust on Dandelion ,仅用作个人学习和记录。如有帮助,请关注原作者,给原作者点赞。
1. Meaning
- *args and **kwargs are mainly used to define the variable parameters of the function
- *args: Send a variable number of non-key-value arguments to the function
- **kwargs: Send a variable number of argument lists of key-value pairs to the function
- If you want to use named variables (like dictionaries) inside a function, use **kwargs
The purpose of defining variable parameters is to simplify
the role of calling * and ** here: packing parameters
2. Precautions when using
- *args and **kwargs are not fixed, only the front * and ** are fixed and immutable, and the latter names can be changed at will. For example, *vals represents a variable number of parameters that are not key-value pairs, and **parms represents variable parameters. Variable number of key-value pair arguments. Using *args and **kwargs is a customary convention, and you don't have to use this name.
- When using *args and **kwargs at the same time, *args must be written before **kwargs.
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)
- Pack multiple parameters 'name', 'age', 'address', 'sex' received by the function test_args() into a tuple ('name', 'age', 'address', 'sex'), Assigned to the formal parameter args.
test_args('name', 'age', 'address', 'sex')
"""输出结果
('name', 'age', 'address', 'sex')
"""
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}
"""