python的*args和**kw

1、关于*args,**keywords的使用。?!

*args----->可以用来在一个方法里面传人多个参数(而且参数的个数可以不确定)

例如,如果不使用*args:

>>> def f(num):
... for i in num:
... print i
...
>>> a = (1,3,5)
>>> f(a)
1
3
5

在这里没有使用*args,所以f()中要传个元组或列表,而不能直接调用f(1,3,5),如下:

>>> f(1,3,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 1 argument (3 given)
>>>

如果f中的参数不是num而是*args,那么f(1,3,5)就可以了,如:

>>> def f2(*args):
... for i in args:
... print i
...
>>> f2(1,3,5)
1
3
5
>>>

不过这个时候有的使用*args的方法中反倒不能传入元组或是列表了,如:

# 带有*的参数方法

>>> def calc(*num):
... sum = 0
... for n in num:
... sum = sum + n
... return sum
...

# 传人多个参数,可以正常输出
>>> calc(1,3,5)
9

# 这里b是一个元组,b = (1,3,5),然后就会报错
>>> calc(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in calc
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
>>>

因为在这里calc的方法中有int + int 的计算,但是传过来的是tuple,就不能与int的相加了,不是说含有*参数的方法就不能传入tuple型参数,如:

# 对上面的f2方法传入一个tuple 型参数,可以正常运行

>>> f2(b)
(1, 3, 5)
>>>

同样的,对**kw来说,就是可以传入多个dict型的参数了,如

>>> def student(name,**kw):
... print 'name:',name,kw.keys(),':', kw.values()
...
>>> student('007',age='18')
name: 007 ['age'] : ['18']
>>>

这样,**kw可以用在像我们要注册账号时候,有些事必填项,有些是选填项,name就像必填,age就是选填。

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值