python3 不定长参数

在python的方法中参数可以传递多个值 可以传递指定个值 也可以传递不定个多余的参数可以用*name和**keyname这样形式的形参来接收

被*name1接收的参数自动转化为一个元组 而被**name2接受的参数变为字典

MacdeMacBook-Pro:test hpb$ cat 不定长.py 
def test(a,b,c=33,*args,**keyname):
    print('a',a,type(a))
    print('b',b,type(b))
    print('c',c,type(c))
    print('args:',args,type(args))
    print('keyname:',keyname,type(keyname))

test(11,22,33,44,55,haha=666,hehe=777)
MacdeMacBook-Pro:test hpb$ python3 不定长.py 
a 11 <class 'int'>
b 22 <class 'int'>
c 33 <class 'int'>
args: (44, 55) <class 'tuple'>
keyname: {'haha': 666, 'hehe': 777} <class 'dict'>
MacdeMacBook-Pro:test hpb$ 

单纯多余的数字 例如44 55  会被 *name1接收

name=666此种形式的会被**name1接收

#注意不能66,name=11,77,name2=22  这种混着用 要不然会报错

要是* 和**作为实参时用来把原组和字典拆开 把它里面的值当做参数传递

MacdeMacBook-Pro:test hpb$ cat 不定长.py 
def test(a,b,c=33,*args,**keyname):
    print('a',a,type(a))
    print('b',b,type(b))
    print('c',c,type(c))
    print('args:',args,type(args))
    print('keyname:',keyname,type(keyname))

if __name__=='__main__':
    a=(100,200,300)
    b={'h':100,'e':111}
    test(11,22,33,44,55,*a,**b,haha=666,hehe=777)
MacdeMacBook-Pro:test hpb$ py3 不定长.py 
a 11 <class 'int'>
b 22 <class 'int'>
c 33 <class 'int'>
args: (44, 55, 100, 200, 300) <class 'tuple'>
keyname: {'h': 100, 'e': 111, 'haha': 666, 'hehe': 777} <class 'dict'>
MacdeMacBook-Pro:test hpb$ 

猜你喜欢

转载自blog.csdn.net/weixin_38280090/article/details/85623286
今日推荐