詳細介紹Python函數(shù)參數(shù)的傳遞的方法
Python函數(shù)參數(shù)是計算機常用的計算機語言,但是在其運行的過程中會有些困難,例如, Python函數(shù)參數(shù)與命令行參數(shù)ython中函數(shù)參數(shù)的傳遞是通過賦值來傳遞的。下面就是關(guān)于其的介紹,希望你會有所收獲。
函數(shù)參數(shù)的使用又有倆個方面值得注意:
- >>> def printpa(**a):
 - ... print type(a)
 - ... print a
 - ...
 - >>> printpa(a=1,y=2)
 - <type 'dict'>
 - F(arg1,arg2,...)
 - {'a': 1, 'y': 2}
 - >>> printpa(a=1)
 - <type 'dict'>
 - {'a': 1}
 - >>> li=[1,2,3,4]
 - >>> printpa(b=li)
 - <type 'dict'>
 - {'b': [1, 2, 3, 4]}
 - >>> tu=(1,2,3)
 - >>> printpa(b=tu)
 - <type 'dict'>
 - {'b': (1, 2, 3)}
 - >>> printpa(1,2)
 - Traceback (most recent call last):
 - File "<stdin>", line 1, in <module>
 - TypeError: printpa() takes exactly 0 arguments (2 given)
 
F(arg1,arg2=value2,...)
是最常見的定義方式,一個函數(shù)可以定義任意個參數(shù),每個參數(shù)間用逗號分割,用這種方式定義的函數(shù)在調(diào)用的的時候也必須在函數(shù)名后的小括號里提供個數(shù)相等的值(實際參數(shù)),而且順序必須相同,也就是說在這種調(diào)用方式中,形參和實參的個數(shù)必須一致,而且必須一一對應(yīng),也就是說***個形參對應(yīng)這***個實參。例如:
- def a(x,y):
 - print x,y
 
調(diào)用該Python函數(shù)參數(shù),a(1,2)則x取1,y取2,形參與實參相對應(yīng),如果a(1)或者a(1,2,3)則會報錯。再看下面的例子:
- >>> a=(1,2,3)
 - >>> def printpa(a):
 - ... print type(a)
 - ... print a
 - ...
 - >>> printpa(a)
 - <type 'tuple'>
 - (1, 2, 3)
 - >>> printpa(range(1,4))
 - <type 'list'>
 - [1, 2, 3]
 - >>> printpa({})
 - <type 'dict'>
 - {}
 - >>> def printpa(a,b,c):
 - ... print a,b,c
 - ...
 - >>> printpa(a)
 - Traceback (most recent call last):
 - File "<stdin>", line 1, in <module>
 - TypeError: printpa() takes exactly 3 arguments (1 given)
 - >>> printpa(*a)
 - 1 2 3
 - >>> a=[1,2,3]
 - >>> printpa(*a)
 - 1 2 3
 - >>> printpa(a)
 - Traceback (most recent call last):
 - File "<stdin>", line 1, in <module>
 - TypeError: printpa() takes exactly 3 arguments (1 given)
 - >>> a=[1,2,3,4]
 - >>> printpa(*a)
 - Traceback (most recent call last):
 - File "<stdin>", line 1, in <module>
 - TypeError: printpa() takes exactly 3 arguments (4 given)
 - >>> printpa(*range(1,4))
 - 1 2 3
 
由上可以看出,如果函數(shù)的有多個形參,調(diào)用的時候可以傳遞一個元組或列表來作實參,但是元組或列表中元素的個數(shù)必須與形參的個數(shù)相同。上述文章是對 Python函數(shù)參數(shù)與命令行參數(shù),ython中函數(shù)參數(shù)的傳遞是通過賦值傳遞的基本應(yīng)用介紹。
【編輯推薦】















 
 
 





 
 
 
 