Python programming learning: introduction to *args and **kwargs (design functions with different numbers of parameters) that make functions more flexible, how to use them, and a detailed guide to classic cases

Python programming learning: introduction to *args and **kwargs (design functions with different numbers of parameters) that make functions more flexible, how to use them, and a detailed guide to classic cases

 

 

 

table of Contents

Introduction to *args and **kwargs (designing different number of parameter functions)

1. *Usage: Count the classmates who signed up to learn basketball in the class, but I don’t know how many names there are

2. **Usage: Count the hobbies of a certain person, but don't know how many hobbies this person has

*args and **kwargs function definition usage method-how to design functions with different numbers of parameters

T1, the most basic approach-create a list as a parameter to pass in (suitable for the case where all values ​​can be enumerated)

T2: *args and **kwargs, the key usage of passing variable number of positional parameters

1. Introduction and usage of *args (list/prime ancestor form, representing any number of unnamed parameters)

(1) Introduction and usage of *args

(2) Solve the above problem-how to design a function with different numbers of parameters

2. Introduction and usage of **kwargs (in the form of a dictionary, which means that there are corresponding keyword parameters one by one)

(1) Introduction and usage of **kwargs

(2) Solve the above problem-how to design a function with different numbers of parameters

Knowledge point expansion: the order of parameters in a function-how to accept a variable number of positional parameters and named parameters?

1. Introduction to the mixed use of arg, *args and **kwargs-args and kwargs can be combined to pass in any number of parameters, which is very effective when the parameters are unknown, and at the same time enhances the scalability of the function .

(1) The case where the default parameters are not included in the function parameters

(2) When the function parameters contain default parameters

(3) When the positional parameters, default parameters, *args*, *kwargs parameters are included at the same time: the correct order is positional parameters→*args*→default parameters→*kwargs)

2. Deeply understand the unpacking asterisk operator-* and **

(1) Use the unpacking operator * to apply to the list output content itself-print() will unpack the list first

(2) How to use multiple unpacking operators*

(3) Use the unpacking operator * to divide the list into three different parts-the first value, the last value and all the values ​​in between

(4) Use the unpacking operator * to merge the two list lists-use * to unpack iterable objects (lists and strings)

(5) Use the unpacking operator * to unpack the string: two methods

(6) Use the unpack operator **unpack dictionary object-** merge the two dict dictionaries

*args and **kwargs function call usage


 

 

 

Introduction to *args and **kwargs (design functions with different numbers of parameters)

        *args and **kwargs are two forms of variable parameters in Python programming. The two of them represent variables and indicate that they can receive variable-length parameters . have to be aware of is

  • The names of args and kwargs are not important, they are just a naming rule established by convention, representing "parameters" and "keyword parameters" respectively, so of course, any other appropriate parameter names can be used, such as *ar and **kw;
  • *args must be placed before **kwargs, because positional parameters are before keyword arguments .
  *args ** kwargs
One sentence explanation Pack the parameters into a tuple and call the function body. The parameter package keyword arguments to dict to the body of the function call.
Features

A plurality of parameters passed to the function, set the count of the number of different parameters of the function, the number of unknown parameters, even length can be zero. *args must be before **kwags, otherwise a syntax error will occur.
Commonly used in function definitions and function calls .

The combination of args and kwargs can pass in any number of parameters, which is very effective when the parameters are unknown, and at the same time strengthens the scalability of the function.

As the name suggests args is the abbreviation of arguments, which means positional parameters; kwargs is the abbreviation of keyword arguments, which means keyword arguments.
usage When we are not sure how many parameters to pass to the function, or when we want to pass the parameters in the form of lists and tuples to the function , we should use *args; When we are not sure how many keyword parameters should be passed into the function, or if we want to use the value of the dictionary as the keyword parameter to pass parameters into the function , we should use **kwargs.
memory args does not contain key, which is packaged into tuple kwargs contains key, that is, package keyword parameters
def a_function(*args, **kwargs):
    pass

 

1. *Usage: Count the classmates who signed up to learn basketball in the class, but I don’t know how many names there are

# 1、*用法:统计一个班内报名学篮球的同学,但是不知道有多少个人名
def CountLearnBasketballs(*basketNums):
    print("People who study basketball have:" + ", ".join(basketNums))


# (1)、用在函数定义中
CountLearnBasketballs('马云','马化腾','李彦宏','刘强东','王兴','丁磊')
# (2)、用在函数调用中
basketNames = ('马云','马化腾','李彦宏','刘强东','王兴','丁磊')
CountLearnBasketballs(*basketNames)


 

2. **Usage: Count the hobbies of a certain person, but don't know how many hobbies this person has

# 2、**用法:统计某个人的爱好,但是不知道这个人有多少种爱好
def CountHobbies(**hobbies):
    print("This person's hobbies include...")
    for category, fave in hobbies.items():
        print(f"{category}: {fave}")

CountHobbies(sports='basketball', arts='drawing', learning='reading')

 

 

*args and **kwargs function definition usage method-how to design functions with different numbers of parameters

T1, the most basic approach-create a list as a parameter to pass in (suitable for the case where all values ​​can be enumerated)

def SUMListsByLists(MoreParasLists):
    sum_lists = 0
    for a in MoreParasLists:
        sum_lists += a
    return sum_lists
MoreParasLists = [1, 2, 3, 4, 5, 6]
print(SUMListsByLists(MoreParasLists))



21

 

 

 

T2: *args and **kwargs, the key usage of passing variable number of positional parameters

1. Introduction and usage of *args (list/prime ancestor form, representing any number of unnamed parameters)

(1) Introduction and usage of *args

        *args is used to pack parameters into tuples and call the function body . They are non-keyword parameters and are used for tuples. At this time, instead of passing a list to the function, it receives positional parameters . The principle is to pass three different positional parameters .

  • The SUMListsByArgs above will get all the input parameters and pack them into a simple iterable object.
  • The object can be named args or other names args123, mainly prefixed with a "*" sign, which is an unpacking operator. However, the iterable object is not a list (variable), but a tuple (immutable) .
def args01(*args):
    print(args, type(args))
args01('一个处女座的程序猿')

def args02(x, y, *args):
    print(x, y, args)
args02(1, 2, 3, 4, '我是','一个处女座的程序猿')







('一个处女座的程序猿',) <class 'tuple'>
1 2 (3, 4, '我是', '一个处女座的程序猿')

 

 

(2) Solve the above problem-how to design a function with different numbers of parameters

def SUMListsByArgs(*args):
    sum_lists = 0
    # Iterating over the Python args tuple
    for a in args:
        sum_lists += a
    return sum_lists
print(SUMListsByArgs(1, 2, 3, 4, 5, 6))




21

 

 

2. Introduction and usage of **kwargs (in the form of a dictionary, which means that there are corresponding keyword parameters one by one)

(1) Introduction and usage of **kwargs

     **kwargs packs the parameters and the keyword parameters are called to the function body in the form of dict . Actually, **kwargs works similarly to *args, but instead of receiving positional parameters, it receives keyword (keyword) parameters (also called named parameters). Similarly, the object can be named kwargs or other names kwargs123, mainly prefixed with "**", which is an unpacking operator. But the iterable object is a dictionary dict, so you need to use .values() to get the return value .

def kwargs01(**kwargs):
    print( kwargs, type(kwargs))
kwargs01(a='一个处女座的程序猿')

def kwargs02(**kwargs):
    print(kwargs)
kwargs02(a='我是', b='一个处女座的程序猿', c='!')






{'a': '一个处女座的程序猿'} <class 'dict'>
{'a': '我是', 'b': '一个处女座的程序猿', 'c': '!'}

 

 

(2) Solve the above problem-how to design a function with different numbers of parameters

def StrConnect(**kwargs):
    strs01='';strs02=''
    # Iterating over the Python kwargs dictionary
    for b in kwargs:
        strs01 += b
    for a in kwargs.values():
        strs02 += a
    print('keys集合:',strs01)
    print('values集合:',strs02)
    return strs02
print(StrConnect(a="大家好", b=",", c="我是", d="一个处女座的程序猿", e="!"))





keys集合: abcde
values集合: 大家好,我是一个处女座的程序猿!
大家好,我是一个处女座的程序猿!

 

 

Knowledge point expansion: the order of parameters in a function-how to accept a variable number of positional parameters and named parameters?

1. Introduction to the mixed use of arg, *args and **kwargs-args and kwargs can be combined to pass in any number of parameters, which is very effective when the parameters are unknown, and at the same time enhances the scalability of the function .

      The combination of args and kwargs can pass in any number of parameters, which is very effective when the parameters are unknown, and at the same time strengthens the scalability of the function.

  • Order is very important. Non-default parameters must be processed before default parameters, so *args comes before **kwargs;
  • The correct order of the parameters: positional parameters → *args parameters → **kwargs parameters, non-default parameters → default parameters; the positions of the three parameters arg, *args, and **kwargs must be constant.
def VariableParasNum_Test(arg,*args,**kwargs):
    print('VariableParasNum_Test')
    print(arg,args,kwargs)
VariableParasNum_Test(1,2,3,4,a=5, b=6, c=7)



VariableParasNum_Test
1 (2, 3, 4) {'a': 5, 'b': 6, 'c': 7}

 

(1) The case where the default parameters are not included in the function parameters

among them

  • x is 1, y is 2;
  • 3,4 are given to args, that is, args=(3,4);
  • a=5,b=6,
  • y=7 is passed to kwargs in dictionary form
def VariableParasNum_NoDefault_Test(x, y, *args,**kwargs):
    print('VariableParasNum_NoDefault_Test')
    print(x, y, args, kwargs)
VariableParasNum_NoDefault_Test(1,2,3,4,a=5,b=6,c=7)    


VariableParasNum_NoDefault_Test
1 2 (3, 4) {'a': 5, 'b': 6, 'c': 7}


 

(2) When the function parameters contain default parameters

There are positional parameters, default parameters, and *args parameters at the same time : the correct order is the following two cases, remember that the positional parameters are all at the forefront

T1, (positional parameter→default parameter→*args)

among them

  • x is 1,
  • The value of y=1 is replaced by 2,
  • 3,4,5 are all given to args, that is, args=(3,4,5)
def VariableParas_IncludeDefault_Test(x,y=1,*args):
    print('VariableParas_IncludeDefault_Test')
    print(x,y,args)
VariableParas_IncludeDefault_Test(1,2,3,4,5)


VariableParas_IncludeDefault_Test
1 2 (3, 4, 5)

 

T2, (positional parameters→*args→default parameters)

among them

  • x is 1,
  • 2,3,4,5 are given to args, that is, args=(2,3,4,5)
  • y is always 1
def ArgsAndDefault_Test(x,*args,y=1):
     print('ArgsAndDefault_Test')
     print(x,args,y)
ArgsAndDefault_Test(1,2,3,4,5)   


ArgsAndDefault_Test
1 (2, 3, 4, 5) 1

 

 

(3) When the positional parameters, default parameters, *args*, *kwargs parameters are included at the same time: the correct order is positional parameters→*args*→default parameters→*kwargs)

among them

  • x is 1, y is 2
  • 3,4 are given to args, that is, args=(3,4)
  • a and b are replaced with 5 and 6 respectively
  • y=7 is passed to kwargs in dictionary form
def VariableParas_IncludeAll_Test(x, y, *args, a=8, b=9, **kwargs):
    print('VariableParas_IncludeAll_Test')
    print(x, y, args, a, b, kwargs)
VariableParas_IncludeAll_Test(1,2,3,4,a=5,b=6,c=7)


VariableParas_IncludeAll_Test
1 2 (3, 4) 5 6 {'c': 7}

 

 

 

2. Deeply understand the unpacking asterisk operator-* and **

The unpacking operator is an operator that unpacks the value of an iterable object in python .

  • * : A single asterisk operator, which can be used on any iterable object provided by python .
  • ** : The two asterisk operators can only be used in dictionaries .

 

(1) Use the unpacking operator * to apply to the list output content itself-print() will unpack the list first

Understanding : print() has taken three different parameters as input instead of a list as input. The package operator (*) is used to call the function, not in the function definition. Here, print() takes a single item in the list as a parameter . As shown below, the output is no longer the list itself, but the content of the list.

lists01 = [1, 2, 3, 4, 5, 6]
print(lists01)
print(*lists01)



[1, 2, 3, 4, 5, 6]
1 2 3 4 5 6

 

(2) How to use multiple unpacking operators*

Use the * operator to unpack a list and pass it to the function as a parameter, as if you were passing each individual parameter. This means that you can use multiple unpacking operators to get values ​​from multiple lists and pass a function as a parameter.

def SUMListsByArgs(*args):
    res = 0
    for x in args:
        res += x
    print(res)
    return res

list01 = [1]
list02 = [2, 3]
list03 = [4, 5, 6]
SUMListsByArgs(*list01, *list02, *list03)






21

 

 

(3) Use the unpacking operator * to divide the list into three different parts-the first value, the last value and all the values ​​in between

One variable is assigned to a, the last one is assigned to c, and the other values ​​are packed into a list b.

lists = [1, 2, 3, 4, 5, 6]
first, *middle, last = lists
print(first, middle, last)




1 [2, 3, 4, 5] 6

 

 

(4) Use the unpacking operator * to merge the two list lists-use * to unpack iterable objects (lists and strings)

list01 = [1, 2, 3]
list02 = [4, 5, 6]
list03 = [*list01, *list02]
print(list03)



[1, 2, 3, 4, 5, 6]

 

 

(5) Use the unpacking operator * to unpack the string: two methods

a   = [*"一个处女座的程序猿"]    # 直接解包
*b, =   "一个处女座的程序猿"     # *将字符串指定到一个新的list 
print(a)
print(b)


['一', '个', '处', '女', '座', '的', '程', '序', '猿']
['一', '个', '处', '女', '座', '的', '程', '序', '猿']

 

 

(6) Use the unpack operator **unpack dictionary object-** merge the two dict dictionaries

dict01 = {'AI':1, 'ML':2, 'DL':3}
dict02 = {'CV':4, 'NLP':4, 'DS':4}
dict03 = {**dict01, **dict02}
print(dict03) 



{'AI': 1, 'ML': 2, 'DL': 3, 'CV': 4, 'NLP': 4, 'DS': 4}


 

 

*args and **kwargs function call usage

       *args and **kwargs can be used not only in function definitions, but also in function calls . When used in the call, it is equivalent to pack (packing) and unpack (unpacking), similar to the packing and unpacking of tuples.

def unpackByargs(arg1, arg2, arg3):
    print(arg1, arg2, arg3)
args = ("一个处女座的程序猿", 2021, 315)
unpackByargs(*args)




一个处女座的程序猿 2021 315

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_41185868/article/details/114849352