Args and Kwargs

2024-01-10

Examples From: Python args and kwargs: Demystified – Real Python

这是 星号解包 的进一步深入应用:函数传参。

Args 变长传参

Passing Multiple Arguments to a Function

def my_sum(a, b, c):
    return a + b + c

my_sum(1,2,3)                     #/// call 

缺点是参数的数量是严格固定死的。

Passing a list to a Function

def my_sum(my_integers):
    result = 0
    for x in my_integers:
        result += x
    return result

list_of_integers = [1, 2, 3]     
print(my_sum(list_of_integers))    #/// call

用列表作为入参后,列表可变长,于是变相解决了可变长传参的问题。但它不是真正的可变长传参,只是改变了问题。

Passing Multiple Arguments to a Function using *args

def my_sum(*args):
    result = 0
    # Iterating over the Python args tuple
    for x in args:
        result += x
    return result

print(my_sum(1, 2, 3))            #/// call function 实现的的是多参数效果

注意: args 可以换成其它名字,重点在于 args 前的一个星号起的作用

kwargs Variable in Function

kwargs (=keyword arguments) 用以实现可变长关键字参数

Iterating over the Python kwargs dictionary

def concatenate(**kwargs):
    result = ""
    # Iterating over the Python kwargs dictionary
    for arg in kwargs.values():
        result += arg
    return result

print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))
#/// RealPythonIsGreat!

注意:

  1. kwargs 可以换成其它名字,重点在于 kwargs 前的两个星号

  2. 此时的参数不是字典,而是关键字参数。想想看,其对应的字典参数版本的函数应该怎么写?

Iterating over the keys of the Python kwargs dictionary

def concatenate(**kwargs):
    result = ""
    # Iterating over the keys of the Python kwargs dictionary
    for arg in kwargs:
        result += arg
    return result

print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))
#/// abcde

此例和上例是什么区别?

在传入参数时,a,b,c 都是变量名,但传入后,这些变量名成了同名字符串

Ordering Arguments in a Function

the correct order for your parameters is:

  1. Standard arguments

  2. *args arguments

  3. **kwargs arguments

def my_function(a, b, *args, **kwargs):
    pass

Unpacking With the Asterisk Operators

能接收多种类型的入参

my_list = [1, 2, 3]
print(my_list)       #/// [1, 2, 3]
print(*my_list)      #/// 1 2 3

print() 既能接受 list, 又能接受多参数,比较万能,其实现就会更复杂

复杂的组合

def my_sum(*args):
    result = 0
    for x in args:
        result += x
    return result

list1 = [1, 2, 3]
list2 = [4, 5]
list3 = [6, 7, 8, 9]

print(my_sum(*list1, *list2, *list3))   #// 

解释最后一行!