詳細介紹Python函數參數的傳遞的方法
Python函數參數是計算機常用的計算機語言,但是在其運行的過程中會有些困難,例如, Python函數參數與命令行參數ython中函數參數的傳遞是通過賦值來傳遞的。下面就是關于其的介紹,希望你會有所收獲。
函數參數的使用又有倆個方面值得注意:
- >>> 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,...)
是最常見的定義方式,一個函數可以定義任意個參數,每個參數間用逗號分割,用這種方式定義的函數在調用的的時候也必須在函數名后的小括號里提供個數相等的值(實際參數),而且順序必須相同,也就是說在這種調用方式中,形參和實參的個數必須一致,而且必須一一對應,也就是說***個形參對應這***個實參。例如:
- def a(x,y):
- print x,y
調用該Python函數參數,a(1,2)則x取1,y取2,形參與實參相對應,如果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
由上可以看出,如果函數的有多個形參,調用的時候可以傳遞一個元組或列表來作實參,但是元組或列表中元素的個數必須與形參的個數相同。上述文章是對 Python函數參數與命令行參數,ython中函數參數的傳遞是通過賦值傳遞的基本應用介紹。
【編輯推薦】