Python参数传递
1、常规参数传递
常规的参数传递中,函数调用时传入的参数的个数要和函数定义时声明的参数的数量一致。
def helloWord(a,b,c):
print(a,b,c)
helloWord(1,2,3)
##对应的输出为:
1 2 3
2、带有默认参数的参数传递
在带有默认值得参数传递中,函数在定义的时候就为其参数声明了一个默认值,如果不对这个参数传入对应的实参,函数就会使用默认定义的值来进行运算。
def helloWord(a,b,c,d=4,e=5):
print(a,b,c,d,e)
helloWord(1,2,3)
# 对应的输出为
1 2 3 4 5
注意:带有默认值得参数一定要放在函数参数列表中的最后面!!!
3、参数个数不固定的参数传递
在函数的实际应用中,常常传入的参数的个数是不固定,我们采用*args来接收不定个数的传递。*args会将传入的参数整合成一个元组的形式在函数中使用,具体操作如下:
def helloWord(*args):
print(*args)
helloWord()
helloWord(1,2)
helloWord((3,4))
helloWord((3,4),1,5)
helloWord((3,5),{5,6})
#对应的输出为:
<class 'tuple'>
<class 'tuple'> 1 2
<class 'tuple'> (3, 4)
<class 'tuple'> (3, 4) 1 5
<class 'tuple'> (3, 5) {5, 6}
第一个函数输出的是一个空的元组,其他的函数都将输入的参数整合成了一个元组,元组中可以包含不同的元素。 args仅仅是参数的名称,在定义的时候,可以存在不同的名字。
当有不同的参数传入的时候,可能有部分函数的参数个数是确定,另外一些事不确定的,此时可以选择和args配合使用,例如:
def helloWord(name,*args):
print("the name is : ",name)
print("the args is : ",*args)
helloWord("hell")
helloWord("hell",1,2)
helloWord("hell",(3,4))
helloWord("hell",(3,4),1,5)
helloWord("hell",(3,5),{5,6})
#对应的输出:
the name is : hell
the args is :
the name is : hell
the args is : 1 2
the name is : hell
the args is : (3, 4)
the name is : hell
the args is : (3, 4) 1 5
the name is : hell
the args is : (3, 5) {5, 6}
注意:有多个参数的时候 *args一定要放在参数列表的后面!!!
4、参数不固定的dict形式传递
这种传递的方式主要是默认参数和不定个数参数传递相结合,通过**args的参数定义,可以将以默认参数传入的参数整合成字典的形式进行使用。
def helloWord(**args):
print(type(args),args)
helloWord()
helloWord(a=1)
helloWord(a=1,b=2,c=3)
#对应输出:
<class 'dict'> {}
<class 'dict'> {'a': 1}
<class 'dict'> {'a': 1, 'b': 2, 'c': 3}
第一次的函数调用输出的是一个空字典,其他两次的调用输出的是一个词典结构。
当输入的实参就是一个词典的时候,需要对这个词典进行拆包的操作,也就是将词典拆开成键值对的形式,在将这种键值对以默认参数的形式输入到函数中,再由函数整理成字典的形式。
def helloWord(**args):
print(type(args),args)
aa = {'a':1,'b':2,'c':3}
helloWord(**aa)
#对应的输出:
<class 'dict'> {'a': 1, 'b': 2, 'c': 3}
注意:在传入字典的时候,一定传入的是**dict,代表是将传入的词典进行拆包!!!
5、综合应用def helloWord(a,b=1,*c,**d):
def helloWord(a,b=1,*c,**d):
print(a,b,c,d)
helloWord(2,6,7,8,m=1,n=2,q=3)
#对应的输出为:
2 6 (7, 8) {'m': 1, 'n': 2, 'q': 3}
def helloWord(a,b=1,*c,**d):
print(a)
print(b)
print(c)
print(d)
helloWord(2,(6,7,8),m=1,n=2,q=3)
#对应输出为:
2
(6, 7, 8)
()
{'m': 1, 'n': 2, 'q': 3}