python tutorial: detailed explanation of variable parameters *args and **kwargs

variable parameter

*argsand **kwargsis a special syntax for handling a variable number of arguments in a Python function or method.

  • *argsIs used to pass an indefinite number of positional arguments (Positional Arguments). In a function definition, *argsit 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
  • **kwargsIs used to pass an indefinite number of keyword arguments (Keyword Arguments). In a function definition, **kwargsit 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 *argsand **kwargscan 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.

Guess you like

Origin blog.csdn.net/a772304419/article/details/132891725