search
HomeBackend DevelopmentPython TutorialHow to set and use function parameters in Python

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])

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'

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)

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)

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})

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)

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. 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})

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})

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

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

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}

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
  ....:

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
  ....:

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

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

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;]

:

#!/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)

(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()

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

Statement
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
How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

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...

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

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 Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools