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