不定长数目参数,*args, **kwargs

*args

当函数参数数目不确定时,‘*’将一组位置参数打包成一个参数值容器。

def demo(a, *args):
    print('a:', a)
    print('args:', args)
    print('type of args:', type(args))
    print('length of args:', len(args))

demo(1, 2, 'hello', [])

# 运行结果:
# a: 1
# args: (2, 'hello', [])
# type of args: <class 'tuple'>
# length of args: 3

我们可以把程序中的*args改为*x、*b等等任意的名字,但是Python官方建议使用*args,这样其他人一看就知道这在干嘛。

若*args不是在最后,则需要在参数传入时,需用关键字参数传入*args后面的参数名:

def demo(*args, a):
    print('a:', a)
    print('args:', args)
    print('type of args:', type(args))
    print('length of args:', len(args))

demo(1, 2, 'hello', [], a=3)

# 运行结果:
# a: 3
# args: (1, 2, 'hello', [])
# type of args: <class 'tuple'>
# length of args: 4

**kwargs

**可以将参数收集到一个字典中,参数的名字是字典的键,对应参数的值是字典的值。

def demo(a, **kwargs):
    print('a:', a)
    print('kwargs:', kwargs)
    print('type of kwargs:', type(kwargs))

demo(0, x1=1, x2=2, x3=3)

# 运行结果:
# a: 0
# kwargs: {'x1': 1, 'x2': 2, 'x3': 3}
# type of kwargs: <class 'dict'>

*args和**kwargs组合使用

def demo(a, *args, **kwargs):
    print('a:', a)
    print('args:', args)
    print('kwargs:', kwargs)

demo(0, 8, 9, x1=1, x2=2, x3=3)

# 运行结果:
# a: 0
# args: (8, 9)
# kwargs: {'x1': 1, 'x2': 2, 'x3': 3}

在函数调用中使用*和**

*和**不仅可以在函数定义中使用,还可以在函数调用中使用。在调用时使用就相当于pack(打包)和unpack(解包)。

def demo(a, b, c):
    print('a:{}, b:{}, c:{}'.format(a, b, c))

lst = [1, 2, 3]
demo(*lst)

# 运行结果:
# a:1, b:2, c:3

更简单的一个示例是关于print函数的:

lst = [1, 2, 3]
print(*lst)

# 运行结果:
# a:1, b:2, c:3

最后举一个‘**’的例子

def demo(a, b, c):
    print('a:{}, b:{}, c:{}'.format(a, b, c))

score = {'a':90, 'b':85, 'c':76}
demo(**score)

# 运行结果:
# a:90, b:85, c:76
原文地址:https://www.cnblogs.com/picassooo/p/12868603.html