Python语言中参数中*和**的作用

*args是非关键字参数,用于元组,**kw是关键字参数,用于字典
看一个综合实例:

def func1(a1,b1=0,*args,**kw):
    print("a1=",a1,"b1=",b1,"args=",args,"kw=",kw)

func1(1,2,3,4,5,6,a=1,b=2,c=3)

输出:

a1= 1 b1= 2 args= (3, 4, 5, 6) kw= {'a': 1, 'b': 2, 'c': 3}

通过在实参前加一个星号(*)或两个星号(**)来对列表(list)、元组(tuple)或字典(dict)

def func1(*args1):
    print(type(args1))
    print(args1)
    print(*args1)



a = [1,2,3,4,5]  # 列表
b = (1,2,3,4,5)  # 元组
func1(a)
print('\n')
func1(*a)
print('\n')
func1(b)
print('\n')
func1(*b)

输出:

<class 'tuple'>
([1, 2, 3, 4, 5],)
[1, 2, 3, 4, 5]


<class 'tuple'>
(1, 2, 3, 4, 5)
1 2 3 4 5


<class 'tuple'>
((1, 2, 3, 4, 5),)
(1, 2, 3, 4, 5)


<class 'tuple'>
(1, 2, 3, 4, 5)
1 2 3 4 5
def func2(**args2):
    print(type(args2))
    print(args2)

a = {'one':1, "two":"2", "three":"3"}
func2(**a)

func2(a=1,b=2,c=3)

输出:

<class 'dict'>
{'one': 1, 'two': '2', 'three': '3'}
<class 'dict'>
{'a': 1, 'b': 2, 'c': 3}

猜你喜欢

转载自blog.csdn.net/qq_42711815/article/details/89069295