python传递任意数量的实参
1、传递任意的实参
1 def make(*test):#带*号 2 print(test) 3 make("one")#传递一个实参 4 make("one","two")#传递两个实参
2、传递任意数的关键字参数
def test(first,last,**user):#关键字参数两个*号、后面user中像字典
profile = {}
profile["first_name"] = first
profile["last_name"] = last
for key,value in user.items():
profile[key] = value
return profile
duibi = test("add","achengqian",
bd="boy",#关键字参数中间是“=”,与字典有出入,并且bd没有带引号
cd="can")
print(duibi)
*args
是可变参数,args接收的是一个tuple;
**kw
是关键字参数,kw接收的是一个dict。
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
在函数调用的时候,Python解释器自动按照参数位置和参数名把对应的参数传进去。
>>> f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> f1(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> f1(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> f1(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
>>> f2(1, 2, d=99, ext=None)
a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
4、lambda函数的格式
sum = lambda a,b:a+b