Python-magic variables *args and **kwargs

When learning Python, you will always encounter the two magic variables *args and **kwargs, so what are they?

First of all, it does not have to be written *args和**kwargs. Only the * (asterisk) in front of the variable is required. You can also write *var 和**varsit as *args 和**kwargsa common naming convention.
Secondly, they also have a name: parameter group. It is passed to the function through a primitive (non-keyword parameter) or dictionary (keyword parameter) as a parameter group. They are a function without explicitly defined parameters.

1. *argsUsage

*args和**kwargsMainly used for function definition. You can pass an unlimited number of parameters to a function.

The indeterminate meaning here is: I don't know in advance how many parameters the function user will pass to you, so these two keywords are used in this scenario.

*argsIt is used to send a variable number of parameter lists that are not key-value pairs to a function.
Simple example:

>>> def func1(*args):
...  print(args)
...
>>> func1()
()
>>> func1('hao')
('hao',)
>>> func1('hao',123)
('hao',123)

Here is an example to help you understand this concept:

def test_args(arg1, *argv):
    print("变量1:", arg1)
    for arg in argv:
        print("变量参数组参数为:", arg)

test_args('1', '2', '3', '4')
The output result is:

Variable 1:: 1 The
parameters of the variable parameter group are: 2 The parameters of the
variable parameter group are: 3 The parameters of the
variable parameter group are: 4

2. Usage of **kwargs

kwargs allows you to pass key-value pairs (dictionaries) of variable length to a function as parameters. If you want to handle named parameters in a function, you should use kwargs.
Simple example:

>>> def func2(**kwargs):
...  print(kwargs)
...
>>> func2()
{
    
    }
>>> func2(name='tom',age=20)
{
    
    'name':'tom','age'=20}

def test_kwargs(**kwargs):
    for key, value in kwargs.items():
        print("{0} == {1}".format(key, value))

>>> test_kwargs(name="tom")
name == tom

Now you can see how we deal with a key-value pair parameter in a function. This is **kwargsthe basis.

Next, let's talk about how to use it *args和**kwargsto call a function whose parameters are lists or dictionaries.
3. Use *args and **kwargs to call functions

So now we will see how to use it *args和**kwargsto call a function.

  • When calling a function, add before *the sequence object to split the sequence object
  • When calling the function, add before the dictionary object to **indicate that the dictionary object is split into the form of key=val

Simple example 1:

Define a simple function

>>>def get_age(name,age):
...	 print('%s is %s years old' %(name,age))
First use *args:
>>> user = ['tom',20]
>>> get_age(user[0],user[1])
tom is 20 years old
>>> get_age(*user)
tom is 20 years old
Now use **kwargs:
>>> user_dict = ['name':'tom','age':20]
>>> get_age(name='tom',age=20)
tom is 20 years old
>>> get_age(**user_dict)
tom is 20 years old

Example 2:
Suppose you have such a function:

def test_args_kwargs(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)

You can use *args or **kwargs to pass parameters to this function. Here is how to do it:

First use *args:
>>> args = ("two", 3, 5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5
Now use **kwargs:
>>> kwargs = {
    
    "arg3": 3, "arg2": "two", "arg1": 5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3

If you want to use standard parameters, *args and **kwargs in the function at the same time, the order is as follows:
some_func(fargs, *args, **kwargs)

4 scenes used

Depends on needs. The most common use case is when writing function decorators.

In addition, it can also be used for monkey patching. Monkey patching means to modify some code at runtime. For example, you have a class with a function called get_info that will call an API and return the corresponding data. If you want to test it, you can replace the API call with some test data. E.g:

import someclass
def get_info(self, *args):
    return "Test data"

someclass.get_info = get_info

Guess you like

Origin blog.csdn.net/weixin_45942735/article/details/104545050