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

How to set and use function parameters in Python

Mar 06, 2017 pm 01:34 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles