Home > Backend Development > Python Tutorial > How to set and use function parameters in Python

How to set and use function parameters in Python

高洛峰
Release: 2017-03-06 13:34:20
Original
2005 people have browsed it

1. Parameters and shared references:

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])
Copy after login

Function parameters are assigned values ​​and passed through variables when calling To implement shared objects, remote modification of variable object parameters in functions can affect the caller.

Avoid variable parameter modification:

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'
Copy after login

2. Specific parameter matching model:

Function matching syntax:

How to set and use function parameters in Python

Example:

Keyword parameters:

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)
Copy after login

Default parameters:

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)
Copy after login

3. Any parameters:

1. Collection parameters:

#*和**出现在函数定义或函数调用中。

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})
Copy after login

2. Unpacking parameters:

Note: Do not confuse The syntax of */** in the function header or function call: in the header means collecting any number of parameters, and in the call, it connects 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']=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)
Copy after login

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
Copy after login

4. The apply built-in function is abandoned in python3.

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})
Copy after login

4. Keyword-only parameters in python3.x

python3.x generalizes the sorting rules of function headers, allowing We specify keyword-only parameters, that is, parameters that are passed according to keywords and will not be filled by a positional parameter; after the parameter *args, the keyword syntax must be called to pass.

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})
Copy after login

1. Sorting rules:

** cannot appear alone in the parameters. The following are incorrect usages :

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
Copy after login

That is to say, in a function header, keyword-only parameters must be written before any keyword form of *args, or appear before or after args. , and may be included in **args.

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
Copy after login

2. Why use keyword-only parameters?

It is easy to allow a function to accept any number of Handling positional arguments, which also accept configuration options passed as keywords, can reduce code that would otherwise have to use *args and **args and manually check keywords.

3. Min calls

to write a function that can calculate the minimum value in any parameter set and any object data type set.

Method 1: Use slicing

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 {&#39;x&#39;: 4, &#39;y&#39;: 5}

In [20]: f(1,c=7,*(2,3),**dict(x=4,y=5)) #keyword-only在
1 (2, 3) 7 {&#39;x&#39;: 4, &#39;y&#39;: 5}
In [21]: f(1,*(2,3),**dict(x=4,y=5,c=7))
1 (2, 3) 7 {&#39;x&#39;: 4, &#39;y&#39;: 5}
Copy after login

Method 2: Let python obtain it automatically to avoid slicing.

In [23]: def min(*args):
  ....: res=args[0]
  ....: for arg in args[1:]:
  ....: if arg < res:
  ....: res = arg
  ....: return res
  ....:
Copy after login

Method 3: Call the built-in function list, convert the ancestor into a list, and then call the built-in sort method of list. Note: Because the python sort routine is written in C and uses a highly optimized algorithm, the running speed is much faster than the first two.

In [28]: def min2(first,*rest):
  ....: for arg in rest:
  ....: if arg < first:
  ....: first = arg
  ....: return first
  ....:
Copy after login

5. Example:

1. Simulate the general set function:

Write a function to return the common part of the two sequences, and write the inter2.py file as follows:

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
Copy after login

Test:

#!/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
Copy after login

2. Simulate python 3.x print function

Write the file python30.py

(1) Use *args Interaction results with **args method

environment python2.7

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]: ([&#39;S&#39;, &#39;A&#39;, &#39;M&#39;], [&#39;S&#39;, &#39;P&#39;, &#39;A&#39;, &#39;M&#39;, &#39;C&#39;])
In [6]: intersect([1,2,3],(1,4))
Out[6]: [1]
In [7]: intersect(s1,s2,s3)
Out[7]: [&#39;S&#39;, &#39;A&#39;, &#39;M&#39;]
In [8]: union(s1,s2,s3)
Out[8]: [&#39;S&#39;, &#39;P&#39;, &#39;A&#39;, &#39;M&#39;, &#39;C&#39;, &#39;L&#39;]
Copy after login

:

#!/usr/bin/python
import sys
def print30(*args,**kargs):
  sep = kargs.get(&#39;sep&#39;,&#39; &#39;)
  end = kargs.get(&#39;end&#39;,&#39;\n&#39;)
  file = kargs.get(&#39;file&#39;,sys.stdout)
  if kargs:raise TypeError(&#39;extra keywords: %s&#39; %kargs)
  output = &#39;&#39;
  first = True
  for arg in args:
    output += (&#39;&#39; if first else sep)+str(arg)
    first = False
  file.write(output + end)
Copy after login

(2) Use the keyword-only method to achieve the same effect as method one:

In [5]: print30(1,2,3)
1 2 3
In [6]: print30(1,2,3,sep=&#39;&#39;)
123
In [7]: print30(1,2,3,sep=&#39;...&#39;)
1...2...3
In [8]: print30(1,[2],(3,),sep=&#39;...&#39;)
1...[2]...(3,)
In [9]: print30(4,5,6,sep=&#39;&#39;,end=&#39;&#39;)
456
In [11]: print30(1,2,3)
1 2 3

In [12]: print30()
Copy after login

More function parameter settings in Python and Please pay attention to the PHP Chinese website for articles related to the method of use!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template