一、參數和共享引用:
In [56]: def changer(a,b): ....: a=2 ....: b[0]='spam' ....: In [57]: X=1 In [59]: L=[1,2] In [60]: changer(X,L) In [61]: X,L Out[61]: (1, ['spam', 2])
函數參數是賦值得來,在呼叫時透過變數實現共享對象,函數中對可變對象參數的在遠處修能夠影響呼叫者。
避免可變參數修改:
In [67]: X=1 In [68]: a=X In [69]: a=2 In [70]: print(X) 1 In [71]: L=[1,2] In [72]: b=L In [73]: b[0]='spam' In [74]: print(L) ['spam', 2] In [75]: changer(X,L[:]) #不想要函数内部在原处的修改影响传递给它的对象,可以创建一个对象的拷贝 In [77]: changer(a,b) In [78]: def changer(a,b): ....: b=b[:] #如果不想改变传入对象,无论函数怎么调用,同样可以在函数内部进行拷贝。 ....: In [79]: a=2 In [80]: b[0]='spam'
#二、特定參數匹配模型:
#函數匹配語法:
#範例:
關鍵字參數:
In [2]: def f(a,b,c):print (a,b,c) In [3]: f(1,2,3) #位置参数调用 (1, 2, 3) In [4]: f(c=3,b=2,a=1) #关键字参数调用 (1, 2, 3)
預設參數:
In [5]: def f(a,b=2,c=3):print (a,b,c) In [6]: f(1) #给a赋值,b,c使用默认赋值 (1, 2, 3) In [7]: f(a=1) (1, 2, 3) In [8]: f(1,4) (1, 4, 3) In [9]: f(1,4,5) #不适用默认值 (1, 4, 5) In [10]: f(1,c=6) #a通过位置得到1,b使用默认值,c通过关键字得到6 (1, 2, 6)
#三、任意參數:
# #1、收集參數:
#*和**出现在函数定义或函数调用中。 In [11]: def f(*args):print (args) In [12]: f() #将所有位置相关的参数收集到一个新的元祖中 () In [13]: f(1) (1,) In [14]: f(1,2,3,4) (1, 2, 3, 4) In [15]: def f(**args):print (args) In [16]: f() {} In [17]: f(a=1,b=2) #**只对关键字参数有效 {'a': 1, 'b': 2} In [19]: def f(a, *pargs,**kargs):print(a,pargs,kargs) In [20]: f(1,2,3,4,5,6,x=1,y=2,z=3) (1, (2, 3, 4, 5, 6), {'y': 2, 'x': 1, 'z': 3})
#2、解包參數:
注意:不要混淆函數頭部或函數呼叫時*/**的語法:在頭部意味著收集任意數量的參數,而在呼叫時,它接駁任意數量的參數。In [21]: def func(a,b,c,d):print(a,b,c,d) In [22]: args=(1,2) In [23]: args += (3,4) In [24]: func(*args) (1, 2, 3, 4) In [25]: args={'a':1,'b':2,'c':3} In [26]: args['d']=4 In [27]: func(**args) (1, 2, 3, 4) In [28]: func(*(1,2),**{'d':4,'c':4}) (1, 2, 4, 4) In [30]: func(1,*(2,3),**{'d':4}) (1, 2, 3, 4) In [31]: func(1,c=3,*(2,),**{'d':4}) (1, 2, 3, 4) In [32]: func(1,*(2,3,),d=4) (1, 2, 3, 4) In [33]: func(1,*(2,),c=3,**{'d':4}) (1, 2, 3, 4)
3、套用函數通用性:
In [34]: def tracer(func,*pargs,**kargs): ....: print ('calling:',func.__name__) ....: return func(*pargs,**kargs) ....: In [35]: def func(a,b,c,d): ....: return a+b+c+d ....: print (tracer(func,1,2,c=3,d=4)) ....: ('calling:', 'func') 10
4、python3.X中廢棄apply內建函數
In [36]: pargs=(1,2) In [37]: kargs={'a':3,'b':4} In [41]: def echo(*args,**kargs):print (args,kargs) In [42]: apply(echo,pargs,kargs) ((1, 2), {'a': 3, 'b': 4})
#
In [43]: echo(*pargs,**kargs) ((1, 2), {'a': 3, 'b': 4}) In [44]: echo(0,c=5,*pargs,**kargs) ((0, 1, 2), {'a': 3, 'c': 5, 'b': 4})
四、python3.x中Keyword-only參數
python3.x把函數頭部的排序規則通用化了,允許我們指定keyword-only參數,也就是按照關鍵字傳遞且不會由一個位置參數來填入的參數;參數*args之後,必須呼叫關鍵字語法來傳遞。In [1]: def kwonly(a,*b,c): ...: print(a,b,c) In [2]: kwonly(1,2,c=3) 1 (2,) 3 In [3]: kwonly(a=1,c=3) 1 () 3 In [4]: kwonly(1,2,3) #c必须按照关键字传递 TypeError: kwonly() missing 1 required keyword-only argument: 'c' In [6]: def kwonly(a,*,b,c):print(a,b,c) In [7]: kwonly(1,c=3,b=2) 1 2 3 In [8]: kwonly(c=3,b=2,a=1) 1 2 3 In [9]: kwonly(1,2,3) TypeError: kwonly() takes 1 positional argument but 3 were given
1、排序規則:
**不能獨自出現在參數中,如下都是錯誤用法:In [11]: def kwonly(a,**pargs,b,c): ....: File "<ipython-input-11-177c37879903>", line 1 def kwonly(a,**pargs,b,c): ^ SyntaxError: invalid syntax In [13]: def kwonly(a,**,b,c): ....: File "<ipython-input-13-46041ada2700>", line 1 def kwonly(a,**,b,c): ^ SyntaxError: invalid syntax
In [14]: def f(a,*b,**d,c=6):print(a,b,c,d) File "<ipython-input-14-43c901fce151>", line 1 def f(a,*b,**d,c=6):print(a,b,c,d) ^ SyntaxError: invalid syntax In [15]: def f(a,*b,c=6,**d):print(a,b,c,d) #keyword-only在*args之后,**args之前 In [16]: f(1,2,3,x=4,y=5) 1 (2, 3) 6 {'x': 4, 'y': 5} In [20]: f(1,c=7,*(2,3),**dict(x=4,y=5)) #keyword-only在 1 (2, 3) 7 {'x': 4, 'y': 5} In [21]: f(1,*(2,3),**dict(x=4,y=5,c=7)) 1 (2, 3) 7 {'x': 4, 'y': 5}
2、為什麼使用keyword-only參數?
很容易允許一個函數既接受任意多個要處理的位置參數,也接受作為關鍵字傳遞的配置選項, 可以減少程式碼,如果沒有它的話,必須使用*args和**args,並且手動地檢查關鍵字。3、min呼叫
寫一個函數,能夠計算任意參數集合和任意物件資料類型集合中的最小值。 方法一:使用切片In [23]: def min(*args): ....: res=args[0] ....: for arg in args[1:]: ....: if arg < res: ....: res = arg ....: return res ....:
In [28]: def min2(first,*rest): ....: for arg in rest: ....: if arg < first: ....: first = arg ....: return first ....:
In [32]: def min3(*args): ....: tmp=list(args) ....: tmp.sort() ....: return tmp[0] ....: In [29]: min2(3,*(1,2,3,4)) Out[29]: 1 In [31]: min(*(5,6,6,2,2,7)) Out[31]: 2 In [33]: min3(3,4,5,5,2) Out[33]: 2
#五、範例:
1、模擬通用set函數:
寫一個函數傳回兩個序列的公共部分,寫inter2.py檔案如下:#
#!/usr/bin/python3 def intersect(*args): res=[] for x in args[0]: for other in args[1:]: if x not in other: break else: res.append(x) return res def union(*args): res=[] for seq in args: for x in seq: if not x in res: res.append(x) return res
In [3]: from inter2 import intersect,union In [4]: s1,s2,s3="SPAM","SCAM","SLAM" In [5]: intersect(s1,s2),union(s1,s2) Out[5]: (['S', 'A', 'M'], ['S', 'P', 'A', 'M', 'C']) In [6]: intersect([1,2,3],(1,4)) Out[6]: [1] In [7]: intersect(s1,s2,s3) Out[7]: ['S', 'A', 'M'] In [8]: union(s1,s2,s3) Out[8]: ['S', 'P', 'A', 'M', 'C', 'L']
2、模擬python 3.x print函數
寫檔案python30.py(1)使用*args和**args方法環境python2.7#!/usr/bin/python import sys def print30(*args,**kargs): sep = kargs.get('sep',' ') end = kargs.get('end','\n') file = kargs.get('file',sys.stdout) if kargs:raise TypeError('extra keywords: %s' %kargs) output = '' first = True for arg in args: output += ('' if first else sep)+str(arg) first = False file.write(output + end)
##互動結果:
In [5]: print30(1,2,3) 1 2 3 In [6]: print30(1,2,3,sep='') 123 In [7]: print30(1,2,3,sep='...') 1...2...3 In [8]: print30(1,[2],(3,),sep='...') 1...[2]...(3,) In [9]: print30(4,5,6,sep='',end='') 456 In [11]: print30(1,2,3) 1 2 3 In [12]: print30()
(2)使用keyword-only方法,實現效果和方法一一樣:
#!/usr/bin/python3 import sys def print30(*args,sep=' ',end='\n',file=sys.stdout): output = '' first=True for arg in args: output += ('' if first else sep) + str(arg) first = False file.write(output + end)
更多Python中函數參數設定及使用的方法相關文章請關注PHP中文網!