python 引數傳遞總結
阿新 • • 發佈:2018-12-29
引數的傳遞
python中函式的引數通過賦值的方式來傳遞引用物件。下面總結通過總結常見的函式引數定義方式,來理解引數傳遞的流程。
def foo(p1,p2,p3,…)
這種方式最常見了,列出有限個數的引數,並且彼此之間用逗號隔開。在呼叫函式的時候,按照順序以此對引數進行賦值,特備註意的是,引數的名字不重要,重要的是位置。而且,必須數量一致,一一對應。第一個物件(可能是數值、字串等等)對應第一個引數,第二個對應第二個引數,如此對應,不得偏左也不得偏右。
>>> def foo(p1,p2,p3): ... print "p1==>",p1 ... print "p2==>",p2 ... print "p3==>",p3 ... >>> foo("python",1,["hiekay","github","io"]) #一一對應地賦值 p1==> python p2==> 1 p3==> ['hiekay', 'github', 'io'] >>> foo("python") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes exactly 3 arguments (1 given) #注意看報錯資訊 >>> foo("python",1,2,3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes exactly 3 arguments (4 given) #要求3個引數,實際上放置了4個,報錯
def foo(p1=value1,p2=value2,…)
這種方式比前面一種更明確某個引數的賦值,貌似這樣就不亂子了,很明確呀。頗有一個蘿蔔對著一個坑的意味。
還是上面那個函式,用下面的方式賦值,就不用擔心順序問題了。
>>> foo(p3=3,p1=10,p2=222)
p1==> 10
p2==> 222
p3==> 3
也可以採用下面的方式定義引數,給某些引數有預設的值
>>> def foo(p1,p2=22,p3=33): #設定了兩個引數p2,p3的預設值 ... print "p1==>",p1 ... print "p2==>",p2 ... print "p3==>",p3 ... >>> foo(11) #p1=11,其它的引數為預設賦值 p1==> 11 p2==> 22 p3==> 33 >>> foo(11,222) #按照順序,p2=222,p3依舊維持原預設值 p1==> 11 p2==> 222 p3==> 33 >>> foo(11,222,333) #按順序賦值 p1==> 11 p2==> 222 p3==> 333 >>> foo(11,p2=122) p1==> 11 p2==> 122 p3==> 33 >>> foo(p2=122) #p1沒有預設值,必須要賦值的,否則報錯 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes at least 1 argument (1 given)
def foo(*args)
這種方式適合於不確定引數個數的時候,在引數args前面加一個*,注意,僅一個喲。
>>> def foo(*args): #接收不確定個數的資料物件
... print args
...
>>> foo("hiekay.github.io") #以tuple形式接收到,哪怕是一個
('hiekay.github.io',)
>>> foo("hiekay.github.io","python")
('hiekay.github.io', 'python')
上一講中已經有例子說明,可以和前面的混合使用。此處不贅述。
def foo(**args)
這種方式跟上面的區別在於,必須接收類似arg=val形式的。
>>> def foo(**args): #這種方式接收,以dictionary的形式接收資料物件
... print args
...
>>> foo(1,2,3) #這樣就報錯了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 0 arguments (3 given)
>>> foo(a=1,b=2,c=3) #這樣就可以了,因為有了鍵值對
{'a': 1, 'c': 3, 'b': 2}
下面來一個綜合的,看看以上四種引數傳遞方法的執行順序
>>> def foo(x,y=2,*targs,**dargs):
... print "x==>",x
... print "y==>",y
... print "targs_tuple==>",targs
... print "dargs_dict==>",dargs
...
>>> foo("1x")
x==> 1x
y==> 2
targs_tuple==> ()
dargs_dict==> {}
>>> foo("1x","2y")
x==> 1x
y==> 2y
targs_tuple==> ()
dargs_dict==> {}
>>> foo("1x","2y","3t1","3t2")
x==> 1x
y==> 2y
targs_tuple==> ('3t1', '3t2')
dargs_dict==> {}
>>> foo("1x","2y","3t1","3t2",d1="4d1",d2="4d2")
x==> 1x
y==> 2y
targs_tuple==> ('3t1', '3t2')
dargs_dict==> {'d2': '4d2', 'd1': '4d1'}