One, parameters and shared references:
In []: Def changer (A, B): .....: a=2 ....: b[0]= ' spam ' .... : In []: x=1in []: L=[1,2]in [ Max]: Changer (x,l) in [Max]: x,lout[61]: (1, [' Spam ', 2])
The function arguments are worthy to be assigned, and when invoked, the shared object is implemented by a variable, and the remote repair of variable object parameters in the function can affect the caller.
Avoid variable parameter modifications:
In [x=1in]: a=xin []: a=2in []: Print (X) 1In [Sat]: L=[1,2]in []: B=lin []: b[0]= ' spam ' in []: Print (L) [' s Pam ', 2]in []: Changer (x,l[:]) #不想要函数内部在原处的修改影响传递给它的对象, you can create a copy of an object in [all]: Changer (A, b) in []: def changer (A, B): .... : b=b[:] #如果不想改变传入对象, no matter how the function is called, it can also be copied inside the function. ....: in []: a=2in []: b[0]= ' spam '
Second, the specific parameter matching model:
function matching syntax:
Example:
Keyword parameters:
In [2]: def f (a,b,c):p rint (A,b,c) in [3]: F (All-in-All) #位置参数调用 (1, 2, 3) in [4]: F (c=3,b=2,a=1) #关键字参数调用 (1, 2, 3)
Default parameters:
In [5]: def f (a,b=2,c=3):p rint (A,b,c) in [6]: F (1) #给a赋值, b,c using default Assignment (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 []: F (1,c=6) #a通过位置得到1, B uses default value, C gets 6 by keyword (1, 2, 6)
Three, arbitrary parameters:
1. Collect parameters:
#* and * * appear in function definitions or function calls. In [all]: def f (*args):p rint (args) in [inch]: F () #将所有位置相关的参数收集到一个新的元祖中 () in [[]: F (1) (1,) in []: F (1,2,3,4) (1, 2, 3, 4) in [+]: def f (**args):p rint (args) in [+]: F () {}in [+]: F (a=1,b=2) #** only valid for keyword parameters {' A ': 1, ' B ': 2}in []: def f (A, *pargs , **kargs):p rint (A,pargs,kargs) in []: 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, Unpacking parameters:
Note: Do not confuse function headers or function calls with the syntax of */**: In the head means to collect any number of arguments, and when called, it is connected to any number of arguments.
in [+]: def func (a,b,c,d):p rint (a,b,c,d) in [+]: args= (in) []: args + = (3,4) in []: Func (*args) (1, 2, 3, 4) in [25]: Args={' A ': 1, ' B ': 2, ' C ': 3}in []: args[' d ']=4in [+]: func (**args) (1, 2, 3, 4) in []: Func (* (), **{' d ': 4, ' C ': 4}) (1, 2, 4, 4) in [+]: func (1,* (2,3), **{' d ': 4}) (1, 2, 3, 4) in [+]: Func (1,c=3,* (2,), **{' d ': 4}) (1, 2, 3, 4) in [+]: func (1,* (2,3,) , d=4) (1, 2, 3, 4) in [+]: Func (1,* (2,), c=3,**{' d ': 4}) (1, 2, 3, 4)
3, Application function versatility:
In [the]: Def Tracer (Func,*pargs,**kargs): ....: Print (' Calling: ', func.__name__) ... .: Return func (*pargs,** Kargs) .... : in [+]: 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. Deprecated apply built-in functions in X
In [approx]: pargs= (+) in [PNS]: kargs={' A ': 3, ' B ': 4}in [+]: def Echo (*args,**kargs):p rint (Args,kargs) in []: Apply (Echo, Pargs,kargs) ((1, 2), {' A ': 3, ' B ': 4})
Using the unpack call syntax, replace:
in [+]: Echo (*pargs,**kargs) ((1, 2), {' A ': 3, ' B ': 4}) in []: Echo (0,c=5,*pargs,**kargs) ((0, 1, 2), {' A ': 3, ' C ': 5, ' B ' : 4})
Iv. keyword-only parameters in python3.x
Python3.x the collation of the function header, allowing us to specify the Keyword-only parameter, which is a parameter that is passed by keyword and is not populated by a positional parameter; After the parameter *args, the keyword syntax must be called to pass.
In [1]: def kwonly (a,*b,c): ...: print (A,b,c) in [2]: Kwonly (1,2,c=3) 1 (2,) 3In [3]: Kwonly (a=1,c=3) 1 () 3In [4]: Kwon Ly (#c必须按照关键字传递TypeError): Kwonly () Missing 1 required keyword-only argument: ' C ' in [6]: def kwonly (a,*,b,c):p rint (A , B,c) in [7]: Kwonly (1,c=3,b=2) 1 2 3In [8]: Kwonly (c=3,b=2,a=1) 1 2 3In [9]: Kwonly () typeerror:kwonly () takes 1 Positi Onal argument but 3 were given
1. Sorting rules:
* * cannot appear alone in parameters, such as the following are error usages:
In [all]: def kwonly (a,**pargs,b,c): ....: File "
", line 1def kwonly (a,**pargs,b,c): ^ Syntaxerror:invalid syntaxin [+]: def kwonly (a,**,b,c): ....: File "
", line 1def kwonly (a,** , b,c): ^syntaxerror:invalid syntax
In other words, a function head, the keyword-only parameter must be written before *args any keyword, either before or after args, and may be included in **args.
in [+]: def f (a,*b,**d,c=6):p rint (a,b,c,d) File "
", Line 1def F (a,*b,**d,c=6):p rint (a,b,c,d) ^ Syntaxerror:invalid syntaxin [+]: def f (a,*b,c=6,**d):p rint (a,b,c,d) #keyword-only after *args, **args before [+]: f (A x=4,y=5) 1 (2, 3) 6 {' X ': 4, ' y ': 5}in []: F (1,c=7,* (2,3), **dict (x=4,y=5)) #keyword-only at 1 (2, 3) 7 {' X ': 4, ' y ': 5}in [2 1]: F (1,* (2,3), **dict (x=4,y=5,c=7)) 1 (2, 3) 7 {' X ': 4, ' Y ': 5}
2, why use keyword-only parameters?
It is easy to allow a function to accept any number of positional parameters to be processed, as well as the configuration options passed as a keyword, to reduce the code, and if it does not, you must use *args and **args, and manually check the keywords.
3, Min call
Write a function that evaluates to the minimum value in any set of parameters and any object data type.
Method One: Use slices
In [all]: def min (*args): ....: res=args[0] .... : For ARG in args[1:]: .....: If arg < res: ....: res = a RG ....: Return res .... :
Method Two: Let Python get it automatically, avoid slicing.
in [+]: def min2 (first,*rest): ....: For Arg in rest: ...: If arg < first: ....: first = arg .... : RE Turn First ....:
Method Three: Call the built-in function list, convert the meta-ancestor to a list, and then invoke the list's built-in sort method implementation. Note: Because Python sort Lie Cheng is written in C, using a highly optimized algorithm runs much faster than the first 2.
in [+]: def min3 (*args): ....: tmp=list (args) .... : Tmp.sort () ....: return tmp[0] ....: in [29]: Min2 (3,* (1,2,3,4)) out[29]: 1In [to]: Min (* (5,6,6,2,2,7)) out[31]: 2In []: min3 (3,4,5,5,2) out[33]: 2
V. Examples:
1. Analog Universal Set Function:
Write a function to return the public part of the two sequence, and write the inter2.py file as follows:
#!/usr/bin/python3def intersect (*args): res=[] for x in Args[0]: for other in Args[1:]: if x not in other : Break Else: res.append (x) return resdef Union (*args): res=[] for seq in args: For x in seq:< C10/>if not X in res: res.append (x) return res
Test:
In [3]: from Inter2 import Intersect,unionin [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,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. Simulate Python 3.x print function
Writing a file python30.py
(1) using *args and **args methods
Environmental python2.7
#!/usr/bin/pythonimport sysdef 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
Interaction results:
In [5]: Print30 (1 2 3In [6]: Print30 (1,2,3,sep= ") 123In [7]: Print30 (1,2,3,sep= ' ... ') 1...2...3In [8]: Print30 (1,[2 ], (3,), sep= ' ... ') 1 ... [2] ... (3,) In [9]: Print30 (4,5,6,sep= ", end=") 456In [All]: Print30 (1) 2 3In []: Print30 ()
(2) Use the Keyword-only method to achieve the same effect as the method:
#!/usr/bin/python3import sysdef 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)