The use of *[parameter name] and **[parameter name] of Python functions

1. *[Parameter name]

transfer

Legal call

Ordinary call

*参数名Generally written *args, such as:

def func(*args):
	print(args)

You can try to call func:

>>> func(1)
(1,)
>>> func()
()
>>> func(1, 2, 3)
(1, 2, 3)
>>> func(dict(), set(), str(), int())
({
    
    }, set(), '', 0)

Therefore, we found that such a function can pass any number of parameters (including 0), and *will pack the parameters into one tuple, such as (1,) () (1, 2, 3) ({}, set(), '', 0).

Special call

What if you already have an tupleobject and want to pass argsit in?
First define an tupleobject:

>>> tuple_object = (1, 2, 3)
>>> print(tuple_object)
(1, 2, 3)
Wrong way

Generally think of this method:

>>> func(tuple_object)
((1, 2, 3),)

((1, 2, 3),)? Shouldn't it be (1, 2, 3)?
Because the system recognizes it as a argsparameter in the middle, it argsis " tuplein the middle tuple", which is wrong. OH NO!

The right way

To tuple_objectplaying in front of a *, OK:

>>> func(*tuple_object)
(1, 2, 3)

This is "unpacking".

Illegal call

What if it is called func(a=1, b=2)? Please see:

>>> func(a=1, b=2)

Get TypeError:

Traceback (most recent call last):
  File "<*args test file>", line 1, in <module>
    func(a=1, b=2)
TypeError: func() got an unexpected keyword argument 'a'

keyword argumentWhat is in the error ?

  • keyword argumentIt is a a=1 b=2 c='Hi'form of passing parameters like this.
  • Simply put, it keyword argumentis a name=valueform of transfer of parameters.

Therefore, you should use valueformal parameter transfers (in English positional argument) instead of using name=valueparameter transfers.

Default parameters

*[参数名]The parameters cannot have default parameters:
Attempt to set the default parameters failed graph
as shown in the figure above, try to set the default parameters will report SyntaxError, if you really want to set the default parameters, you should use a method similar to "manually set default values":

# 手动设置*args的参数默认值
DEFAULT_VALUE = (1, 2, 3) # 默认值,可自行改变
def func(*args):
	if args == (): # 如果为空(用户没有传递参数):
		args = DEFAULT_VALUE # 设为默认值
	print(args)

In this way, there are default values:

>>> func() # 无参数调用
(1, 2, 3)

to sum up

  • *[参数名]Indicates that valueformal parameters should be used , and the number of parameters is not limited. After being passed in, they will be packaged tuplefor use in the function body.
  • Special parameter transfer method:*[tuple object]
  • This method cannot set the default value, and can only use "Manually set the default value".

2. **[Parameter name]

transfer

Legal call

Ordinary call

**参数名Generally written **kwargs, such as:

def func(**kwargs): # kwargs = keyword arguments
	print(kwargs)

Then call func, but this is the opposite of the previous one, it must be a name=valueparameter pass (this is why it is called kwargs (keyword arguments)):

>>> func(a=1, b=2, c=3, d=4)
{
    
    'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> func(_tuple_obj=tuple(), _set_obj=set(), _dict_obj=dict())
{
    
    '_tuple_obj': (), '_set_obj': set(), '_dict_obj': {
    
    }}
>>> func()
{
    
    }

Such a function can pass any number keyword argument(including 0), here is the opposite of the previous one, the parameters will be packed into one dict, such as {'a': 1, 'b': 2, 'c': 3, 'd': 4} {'_tuple_obj': (), '_set_obj': set(), '_dict_obj': {}} {}.

Special call

What if you already have an dictobject and want to pass kwargsit in?
First define an object like this:

>>> dict_object = {
    
    'a': 666, 'b': 888}
>>> print(dict_object)
{
    
    'a': 666, 'b': 888}

Then, similar to the last time:

>>> func(dict_object) # 因为不能传positional argument, 这下还报错了(马上会讲到):
Traceback (most recent call last):
  File "<**kwargs test program>", line 1, in <module>
    func(dict_object)
TypeError: func() takes 0 positional arguments but 1 was given
>>> func(**dict_object) # 正确方法
{
    
    'a': 666, 'b': 888}

Illegal call

What if it passes positional argument? Please see:

>>> func(1, 2)

Get TypeError:

Traceback (most recent call last):
  File "<**kwargs test program>", line 1, in <module>
    func(1, 2)
TypeError: func() takes 0 positional arguments but 2 were given

Therefore, the key=valueformal parameter transfer (in English keyword argument) should be used valuehere instead of the parameter transfer method.

Default parameters

Similar to *argsthe method, you should use the method of manually setting the default value:

# 手动设置**kwargs的参数默认值
DEFAULT_VALUE = {
    
    'a': 1, 'b': 2} # 默认值,可自行改变
def func(**kwargs):
	if kwargs == {
    
    }: # 如果为空(用户没有传递参数):
		kwargs = DEFAULT_VALUE # 设为默认值
	print(kwargs)

In this way, there are default values:

>>> func() # 无参数调用
{
    
    'a': 1, 'b': 2}

to sum up

  • **[参数名]Indicates that the key=valueparameters should be passed in form, the number of parameters is not limited, and they will be packaged after being passed in dict.
  • Special parameter transfer method:**[dict object]
  • This method cannot set the default value, and can only use "Manually set the default value".

Guess you like

Origin blog.csdn.net/write_1m_lines/article/details/104635431