This article describes how to set and use function parameters in Python, and records differences between Python2.x and function parameters in Python3.x. For more information, see
1. parameters and shared references:
In [56]: def changer(a,b): ....: a=2 ....: b[0]='spam' ....: In [57]: X=1In [59]: L=[1,2]In [60]: changer(X,L)In [61]: X,LOut[61]: (1, ['spam', 2])
Function parameters are assigned values. shared objects are implemented through variables during calls. the remote repair of variable object parameters in functions can affect callers.
Avoid modifying variable parameters:
In [67]: X = 1In [68]: a = XIn [69]: a = 2In [70]: print (X) 1In [71]: L = [1, 2] In [72]: B = LIn [73]: B [0] = 'spam' In [74]: print (L) ['spam ', 2] In [75]: changer (X, L [:]) # objects passed to the function without modifying the function In the original place, you can create an object copy In [77]: changer (a, B) In [78]: def changer (a, B ):....: B = B [:] # If you do not want to change the input object, you can copy the object inside the function no matter how the function is called ..... : In [79]: a = 2In [80]: B [0] = 'spam'
II. matching model with specific parameters:
Function matching syntax:
In [2]: def f (a, B, c): print (a, B, c) In [3]: f (1, 2, 3) # Location parameter call (1, 2, 3) In [4]: f (c = 3, B = 2, a = 1) # keyword parameter call (1, 2, 3)
Default parameters:
In [5]: def f (a, B = 2, c = 3): print (a, B, c) In [6]: f (1) # assign a value to a, B, c using the default value (1, 2, 3) In [7]: f (a = 1) (1, 2, 3) in [8]: f () (1, 4, 3) In [9]: f (, 5) # default values (1, 4, 5) in [10]: f (1, c = 6) # a gets 1 through the position, B uses the default value, c gets 6 through the keyword (1, 2, 6)
III. any parameters:
1. collection parameters:
# * And ** appear in function definition or function call. In [11]: def f (* args): print (args) In [12]: f () # collect parameters related to all locations into a new ancestor () in [13]: f (1) (1,) In [14]: f (1, 3, 4) (1, 2, 3, 4) In [15]: def f (** args): print (args) In [16]: f () {} In [17]: f (a = 1, B = 2) # ** only valid for keyword parameters {'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. unpack parameters:
Note: Do not confuse the */** syntax of the function header or function call: the header means to collect any number of parameters, while the header means to collect any number of parameters.
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']=4In [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. Application function versatility:
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. discard the apply built-in function in python3.X.
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})
Replace:
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})
IV. Keyword-only parameter in python3.x
Python3.x extends the sorting rules of the function header. you can specify the keyword-only parameter, that is, the parameter that is passed according to the keyword and is not filled by a location parameter. after the parameter * args, the keyword syntax must be called for transmission.
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]: kwonly (1, 2, 3) # c must pass TypeError: kwonly () missing 1 required keyword-only argument according to the keyword: 'C' In [6]: def kwonly (a, *, B, c): print (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 (1, 2, 3) TypeError: kwonly () takes 1 positional argument but 3 were given
1. sorting rules:
** It cannot appear in parameters independently. The following are all incorrect operations:
In [11]: def kwonly(a,**pargs,b,c): ....: File "
", line 1def kwonly(a,**pargs,b,c): ^SyntaxError: invalid syntaxIn [13]: def kwonly(a,**,b,c): ....: File "
", line 1def kwonly(a,**,b,c): ^SyntaxError: invalid syntax
That is to say, the keyword-only parameter of a function header must be written before or after any keyword form of * args, and may be included in ** args.
In [14]: def f (a, * B, ** d, c = 6): print (a, B, c, d) File"
", Line 1def f (a, * B, ** d, c = 6): print (a, B, c, d) ^ SyntaxError: invalid syntaxIn [15]: def f (a, * B, c = 6, ** d): print (a, B, c, d) # keyword-only after * args, ** before 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 In 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. Why is the keyword-only parameter used?
It is easy to allow a function to accept any number of location parameters to be processed, as well as configuration options passed as keywords, which can reduce the code without it, you must use * args and ** args and manually check the keywords.
3. min call
Compile a function to calculate the minimum value of any parameter set and any object data type set.
Method 1: Use slice
In [23]: def min(*args): ....: res=args[0] ....: for arg in args[1:]: ....: if arg < res: ....: res = arg ....: return res ....:
Method 2: enable python to automatically obtain and avoid slicing.
In [28]: def min2(first,*rest): ....: for arg in rest: ....: if arg < first: ....: first = arg ....: return first ....:
Method 3: Call the built-in function list, convert the ancestor to the list, and then call the built-in sort method to implement the list. Note: Because the python sort columns are written in C, the high-optimization algorithm is used to run faster than the first two.
In [32]: def min3(*args): ....: tmp=list(args) ....: tmp.sort() ....: return tmp[0] ....:In [29]: min2(3,*(1,2,3,4))Out[29]: 1In [31]: min(*(5,6,6,2,2,7))Out[31]: 2In [33]: min3(3,4,5,5,2)Out[33]: 2
V. example:
1. simulate common set functions:
Compile a function to return the public parts of the two sequences. Compile 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: 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,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. simulate the python 3.x print function
Compile the python30.py file
(1) use the * args and ** args methods
Environment 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 result:
In [5]: print30(1,2,3)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 [11]: print30(1,2,3)1 2 3In [12]: print30()
(2) use the keyword-only method to achieve the same effect as Method 1:
#!/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)
For more information about how to set and use function parameters in Python, see PHP!