python 中*args和**kw 学习笔记

1.实参
def test_0(x,y):#实参x,y
      print (x)
      print (y)
test_0(4,5)

4
5

2.*args:非关键字参数,用于元组


def test_1(x,y,*args):#+args
      print (x)
      print (y)
      print ('the length of args is %s'%len(args))
      print (args)
test_1(1,2,3,4,5,6)

1
2
the length of args is 4
(3, 4, 5, 6)

3.**kw:关键字参数,用于字典

def test_2(x,y,**kw):
      print (x)
      print (y)
      for x in kw:
            print (x,':',str(kw[x]))
test_2(1,2,frala=98,Hua=100)

1
2
frala : 98
Hua : 100

4.*与**合用

 def test_3(x,y,*args,**kw):    #args必须在kw之前
      print (x)
      print (y)
      print ('the length of args is %s'%len(args))
      print (args)
      for x in kw:
            print (x,':',str(kw[x]))
test_3(1,2,3,4,5,6,7,8,frala=98,Hua=100)

1
2
the length of args is 6
(3, 4, 5, 6, 7, 8)
frala : 98
Hua : 100

总结:

    *与**是python中的可变参数,*args:非关键字参数,用于元组,**kw:关键字参数,用于字典。自定义参数后*与**只要不是数字即可。

猜你喜欢

转载自blog.csdn.net/z_feng12489/article/details/79937348