Python中的*args和**kwarg

时间:2024-08-07 22:36:50

可变参数 *args 允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple,

而 关键字参数 **kw 允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict

可变参数*args

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n*n
    return sum

calc(1, 2)
calc()

另一种用法:

numbers = [1, 2, 3]
calc(numbers[0], numbers[1], numbers[2])

calc(*numbers)

关键字参数**kw

# coding=utf8

def person(name, age, **kw):
    print(name, age, 'other: ', kw)

结果:

Python中的*args和**kwarg

命名关键字参数

# 只接受city和job作为关键字参数,这么写:
def person(name, age, *, city, job):
    print(name, age, city, job)

person('Jack', 24, city='Beijing', job='Engineer')
# 由于命名关键字参数city具有默认值,调用时,可不传入city参数:
def person(name, age, *, city='Beijing', job):
    print(name, age, city, job)

person('Jack', 24, job='Engineer')

参数组合

# coding=utf8

def f1(a, b, c=0, *args, **kw):
    print('a = ', a, 'b = ', b, 'c = ', c, 'args = ', args, 'kw = ', kw)

def f2(a, b, c=0, *, d, **kw):
    print('a = ', a, 'b = ', b, 'c = ', c, 'd = ', d, 'kw = ', kw)

args = [1, 2, 3, 4]
kw = {', 'city': 'Beijing'}
f1(*args, **kw)