本文實例總結了python傳遞參數方式。分享給大家供大家參考。具體分析如下:
當形參如*arg時表示傳入數組,當形參如**args時表示傳入字典。
1
2
3
4
5
6
|
def myprint( * commends, * * map ): for comm in commends: print comm for key in map .keys(): print key, map [key] myprint( "hello" , "word" ,username = "tian" ,name = "wei" ) |
輸出:
1
2
3
4
|
hello word username tian name wei |
python中定義一個函數,可以通過正常的只傳入值或key-value的方法調用。但是如果第一個時參數傳入的是key-value的方法,那么后面的必須都是key-value方法,如果第一個不是,那么后面的可以根據情況再傳入值就可以了。
例子如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
def parrot(voltage = "fff" ,state = 'a stiff' ,action = 'voom' , type = 'Norwegian Blue' ): print "-- This parrot wouldn't" , action, print "if you put" , voltage, "volts through it." print "-- Lovely plumage, the" , type print "-- It's" , state, "!" parrot( 1000 ) #可以 parrot(action = 'VOOOOOM' , voltage = 1000000 ) #可以,都是key-value方法 parrot( 'a thousand' , state = 'pushing up the daisies' ) #可以,第一個實參為直接傳入法,后面無所謂了 parrot( 'a million' , 'bereft of life' , 'jump' ) #可以,都是傳值,而且由于形參都有默認值,則按順序一個個替換 parrot(voltage = "33" , "ff" , "abc" ) # 不可以,第一個為Key-value傳值法,以后的都必須是 |
Python新手入門,在python中函式定義主要有四種方式:
① F(arg1,arg2,...),最常見的定義方式,一個函式可以定義任何個參數,每個參數間用逗號分割,用這種參數在調用的時候必須在函式名后面的小括號中提供個數相等的值(實參),并且順序必須相同,形參與實參一一對應
1
2
|
def a(x,y): print x,y |
調用a函式,a(1,2)則x=1,y=2,如果a(1)或者a(1,2,3)則會出錯
② F(arg1,arg2=value2,...agrN=valueN),則將為函式提供默認值。
1
2
|
def a(x,y = 3 ): print x,y |
調用該函式,a(1,2)則x=1,y=2,如果a(1)不會導致錯誤,此時x=1,y=3,y值將使用默認值,a(y=4,x=2)同理
可變參數:
③ F(*arg1),以一個*加形參的方式來表示函式的實參個數不確定,參數個數>=0,采用這樣的方式定義函式,在函式內部將以實參名的方式構建一個元組(tuple)
1
2
3
4
5
6
7
8
9
10
11
12
|
def a( * x): # 定義一個名為x的元組 def a( * t): print x >>>a( 1 ) ( 1 ,) >>>a() None >>>a( 1 , 2 , 3 ) ( 1 , 2 , 3 ) |
遍歷該元組(計算總和)的一種方式,此時r定義為一元組:
1
2
3
4
5
|
def y( * r): x = 0 for t in r: x + = t print x |
④ F(**arg)形參名前加2個**表示在函式內部將被存放在以形參名為標識符的dictionary,這時調用將使用arg1=value1,arg2=value2...
1
2
3
4
5
6
7
8
9
|
def a( * * b): print b >>>a() None >>>a(x = 1 ,y = 2 ) { 'y' : 2 , 'x' : 1 } #注意遍歷返回的順序與形參位置順序相反 >>>a( 1 , 2 ) #error |
可通過以下方式來獲取預期鍵值對,如果形參是未定義'y'的鍵,將返回None
1
2
3
4
5
6
7
8
9
|
def a( * * x): print x.get( 'y' ) >>>a(x = 1 ,y = 2 ) 2 >>>a(x = 1 ) None >>>a(x = 1 ,b = 2 ) None |
Python參數調用過程按照以上四種方法優先級依次降低。
①方式解析,然后是②中的arg=value方式,再分別按照③>④優先級傳參
這是自己第一份通過Blog整理的學習筆記,希望對自己,對瀏覽至此的各位朋友有所幫助,以上函式命名不符合規范,僅用于簡單標識說明,使用python 2.6.2
希望本文所述對大家的Python程序設計有所幫助。