*意味着传入的参数是一个元组或者列表
**意味着传入的变量是一个字典
如果什么也不加意味着传入的是一个整体,如果是数组,就是数组整体,如果是字典,就是字典整体
举例如下:
最好的方法就是跟着例子自己在jupyter notebook里面实现一下:
#表示只有三个参数
def test(arg1,arg2,arg3):
#如果传递过来的是单个变量,就无所谓
def test(a,d,*b,**c):
print("a=%s"%a)
print("d=",d)
for i in b:
print("b=%s"%i)
for key in c:
print("%s:%s"%(key,c[key]))
test(1,"cheng",b="cheng")
>>>a=1
d= cheng
b:cheng
a={"cheng":2,"yi":3}
test(1,2,*a)
>>>a=1
d= 2
b=cheng
b=yi
test(1,a)
>>>a=1
d= {'cheng': 2, 'yi': 3}
test(1,2,**a)
>>>a=1
d= 2
cheng:2
yi:3
再来一些例子:
def test(arg1,arg2,arg3):
print("arg1=",arg1)
print("arg2=",arg2)
print("arg3=",arg3)
#把字典和袁祖都当成普通变量
print(test(1,2,3))
print(test("cheng","yi",3))
a=["cheng","yi"]
print(test("cheng",a,a))
>>>arg1= 1
arg2= 2
arg3= 3
None
arg1= cheng
arg2= yi
arg3= 3
None
arg1= cheng
arg2= ['cheng', 'yi']
arg3= ['cheng', 'yi']
None
#如果传递过去的参数数量不匹配就会报错,如下所示:
#有元组或者列表
test(1,*a)
#如果把数组的程度更改一下就会报错
a=["cheng","yi",'ming']
test(1,*a)
>>>TypeError: test() takes 3 positional arguments but 4 were given
b={"arg2":1,"arg3":2}#注意给键加上双引号
test("cheng",**b)
>>>arg1= cheng
arg2= 1
arg3= 2
test("cheng",arg2=2,arg3=9)
>>>arg1= cheng
arg2= 2
arg3= 9