Summary of knowledge about variable length parameters in Python functions

Time:2022-6-20

1、 Variable length position parameter

#When defining function parameters, you can add * in front of formal parameters, which will obtain all position arguments
#It saves all arguments in a tuple
def fn(*args):
    print("args=", args)
    print("args type:", type(args))


#Parameters with * and other parameters
def fn1(a, b, *args):
    print(a)
    print(b)
    print(args)


#The following two methods can be used, but attention should be paid to when passing arguments
def fn2(*args, a, b):
    print(a)
    print(b)
    print(args)


def fn3(a, *args, b):
    print(a)
    print(args)
    print(b)


if __name__ == "__main__":
    #Receive all position parameters
    fn(1, 2, 3, 4, 5)
    fn1(11, 12, 13, 14)
    #FN2 (21, 22, 23, 24) \
    fn2(21, 22, a=23, b=24)
    #FN3 (21, 22, 23, 24) \
    fn3(21, 22, 23, b=24)

FN operation results

在这里插入图片描述

FN1 operation results

在这里插入图片描述

FN2 operation results

在这里插入图片描述

FN3 operation results

在这里插入图片描述

Summary:

1. there can only be one formal parameter with * and multiple formal parameters will report errors and cannot be recognized

2. formal parameters with * can be used with other parameters, such as those without stars

3. formal parameters with * do not have to be placed at the back, but can be placed at the front, middle and last. Note, however, that all parameters after the parameters with stars must be passed in the form of keyword parameters, or an error will be guaranteed.

2、 Variable length keyword parameter

#Formal parameters with * can only receive location parameters, but keyword parameters cannot
#An error will be reported if FN passes the following values
def fn(*args):
    print("args=", args)
    print("args type:", type(args))

if __name__ == "__main__":
    #The message will be saved. Args cannot receive keyword parameters
    fn(1, 2, 3, 4, a=10)

The operation is as follows:

在这里插入图片描述

#* * formal parameters can receive keyword parameters
#It saves all received keyword parameters in a dictionary
def fn4(**kwargs):
    print("kwargs = ", kwargs)
    print(type(kwargs))

if __name__ == "__main__":
    fn4(a=1, b=2, c=3)

Operation results:

在这里插入图片描述

Summary:

1.* * there can only be one formal parameter, which must be written at the end of all parameters.

2. the key of the dictionary is the name of the parameter, and the value of the dictionary is the value of the parameter

This is the end of this article about the summary of knowledge about variable length parameters in Python functions. For more information about Python variable length parameters, please search the previous articles of developeppaer or continue to browse the following articles. I hope you will support developeppaer in the future!