python 函数参数的传递(参数带星号的说明) 元组传递 字典传递

python 函数参数的传递(参数带星号的说明) 元组传递 字典传递

*arg 代表的是arg元祖,**kwd代表的是kwd名称的字典。 

那函数传参数或是使用参数的时候,什么时候带*号什么时候不带*号呢?我这点总是理解不上来,或者说有点混乱。参考下面几个小函数,来理解下

>>> def a(*x):
print (x)

>>> def b(x):
print(x)


>>> def c(*x):
print(*x)


>>> x = (1,2,3)
>>> a(x)
((1, 2, 3),)
>>> a(*x)
(1, 2, 3)
>>> b(x)
(1, 2, 3)
>>> b(*x)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
b(*x)
TypeError: b() takes 1 positional argument but 3 were given
>>> c(x)
(1, 2, 3)
>>> c(*x)
1 2 3

这样就清楚了。*arg就是要把形参名为arg的列表内容打散。 arg不带星,则表示为列表。

原文地址:https://www.cnblogs.com/ppybear/p/12286257.html