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就是选填。