python 函数参数

关键字参数

def func(a, b=5, c=10):
    print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)

输出:

$ python function_keyword.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

定义函数时指定可变关键字参数的值为None,在函数体内部重新绑定默认参数的值

def good_append(new_item, a_list = None):
    if a_list is None:
        a_list = []
    a_list.append(new_item)
    return a_list

print(good_append('1'))
print(good_append('c', ['a', 'b']))

可变参数

定义的函数里面能够有任意数量的变量,也就是参数数量是可变的,这可以通过使用星号来实现

def total(a=5, *numbers, **phonebook):
    print('a', a)

    #遍历元组中的所有项目
    for single_item in numbers:
        print('single_item', single_item)

    #遍历字典中的所有项目
    for first_part, second_part in phonebook.items():
        print(first_part,second_part)

print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))

输出:

$ python function_varargs.py
a 10
single_item 1
single_item 2
single_item 3
Inge 1560
John 2231
Jack 1123
None

当我们声明一个诸如 *param 的星号参数时,从此处开始直到结束的所有位置参数(Positional Arguments)都将被收集并汇集成一个称为“param”的元组(Tuple)。

类似地,当我们声明一个诸如 **param 的双星号参数时,从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为 param 的字典(Dictionary)

原文地址:https://www.cnblogs.com/qev211/p/14987460.html