variable parameter
*args
and **kwargs
is a special syntax for handling a variable number of arguments in a Python function or method.
*args
Is used to pass an indefinite number of positional arguments (Positional Arguments). In a function definition,*args
it means that any number of positional arguments can be accepted and passed to the function as a tuple. When calling a function, you can pass any number of positional arguments, which will be packed into a tuple and passed to*args
.
For example, the following function accepts any number of positional arguments and adds them:
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
Example of calling method:
result = add_numbers(1, 2, 3, 4) # result = 10
result = add_numbers(10, 20, 30, 40, 50) # result = 150
**kwargs
Is used to pass an indefinite number of keyword arguments (Keyword Arguments). In a function definition,**kwargs
it means that any number of keyword arguments can be accepted and passed to the function as a dictionary. When calling a function, you can pass any number of keyword arguments, which will be packed into a dictionary and passed to**kwargs
.
For example, the following function accepts any number of keyword arguments and prints their key-value pairs:
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{
key}: {
value}")
Example of calling method:
print_kwargs(name="John", age=30, city="New York")
# 输出:
# name: John
# age: 30
# city: New York
Note that *args
and **kwargs
can be used with other parameters, but are usually placed at the end of the parameter list. For example:
def example_func(arg1, arg2, *args, **kwargs):
# 函数体
In a function definition, the order of parameters should be: required parameters, *args
, keyword parameters, **kwargs
. Thus, a function can accept positional arguments, an indefinite number of positional arguments, keyword arguments, and an indefinite number of keyword arguments.