跟老齐学Python之总结参数的传递

2019-10-05 15:43:56于丽

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes at least 1 argument (1 given)

 def foo(*args)

这种方式适合于不确定参数个数的时候,在参数args前面加一个*,注意,仅一个哟。

>>> def foo(*args):         #接收不确定个数的数据对象
...     print args
...
>>> foo("qiwsir.github.io") #以tuple形式接收到,哪怕是一个
('qiwsir.github.io',)
>>> foo("qiwsir.github.io","python")
('qiwsir.github.io', 'python')

 上一讲中已经有例子说明,可以和前面的混合使用。此处不赘述。

def foo(**args)

这种方式跟上面的区别在于,必须接收类似arg=val形式的。

>>> def foo(**args):    #这种方式接收,以dictionary的形式接收数据对象
...     print args
...

>>> foo(1,2,3)          #这样就报错了
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 0 arguments (3 given)

>>> foo(a=1,b=2,c=3)    #这样就可以了,因为有了键值对
{'a': 1, 'c': 3, 'b': 2}

 下面来一个综合的,看看以上四种参数传递方法的执行顺序

>>> def foo(x,y=2,*targs,**dargs):
...     print "x==>",x
...     print "y==>",y
...     print "targs_tuple==>",targs
...     print "dargs_dict==>",dargs
...

>>> foo("1x")
x==> 1x
y==> 2
targs_tuple==> ()
dargs_dict==> {}

>>> foo("1x","2y")
x==> 1x
y==> 2y
targs_tuple==> ()
dargs_dict==> {}

>>> foo("1x","2y","3t1","3t2")
x==> 1x
y==> 2y
targs_tuple==> ('3t1', '3t2')
dargs_dict==> {}

>>> foo("1x","2y","3t1","3t2",d1="4d1",d2="4d2")
x==> 1x
y==> 2y
targs_tuple==> ('3t1', '3t2')
dargs_dict==> {'d2': '4d2', 'd1': '4d1'}

 通过上面的例子,看官是否看出什么名堂了呢?