Introduction to Python's *args and **kwargs parameters

Introduction to python 's *args and **kwargs parameters

Detailed explanation of the parameters of the Python function https://blog.csdn.net/cnds123/article/details/123264378

When defining a function, if you want to receive a variable number of positional or keyword arguments and want to refer to them in the form of tuples or dictionaries, you need to use syntax structures such as *args and **kwargs.

Note that *args and **kwargs are just generic convention names, in fact you can use other names instead. But * and ** are grammatical symbols used to destructure parameters and cannot be removed.

*args and **kwargs are special syntax for handling variable numbers of arguments in function definitions and function calls.

*args accepts any number of positional arguments (positional arguments) that will be passed to the function as a tuple. These parameters can be accessed inside the function by iterating over the tuple. example:

def foo(*args):
    for arg in args:
        print(arg)

foo(1, 2, 3)  # 输出:1 2 3

 **kwargs accepts any number of keyword arguments that will be passed to the function as a dictionary. Inside the function, these parameters can be accessed through the key-value pairs of the dictionary. example:

def bar(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

bar(name='Alice', age=25, city='New York')

Output:
name Alice
age 25
city New York

 

In a function definition, you can use both *args and **kwargs to accept any number of positional and keyword arguments. example:

def baz(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(key, value)

baz(1, 2, 3, name='Bob', age=30)

Output:
1
2
3
name Bob
age 30

 

Guess you like

Origin blog.csdn.net/cnds123/article/details/131223255