原文链接:https://www.programiz.com/python-programming/function-argument
Python Function Arguments
In Python, you can define a function that takes variable number of arguments. You will learn to define such functions using default, keyword and arbitrary arguments in this article.
Table of Contents
函数参数
在python中,你可以定义一个带有参数的变量数量的函数。在这篇文章中你将学习到默认值,关键字和任意参数这样函数。
表格内容
- 参数
- 变量函数参数
- 默认参数
- 关键字参数
- 任意参数
Arguments
In user-defined function topic, we learned about defining a function and calling it. Otherwise, the function call will result into an error. Here is an example.
def greet(name,msg):
"""This function greets to
the person with the provided message"""
print("Hello",name + ', ' + msg)
greet("Monica","Good morning!")
Output
Hello Monica, Good morning!
参数
在用户定义主题中,我们可以学习到定义一个函数和调用它。否则,这函数调用的结果变成一个错误。这里有一个例子。
输出
>>> def greet(name,msg):
... """This function greets to the person with the provided message"""
... print("Hello" ,name + ',' + msg)
...
>>> greet("Monica","Good morning!")
Hello Monica,Good morning!
Here, the function greet()
has two parameters.
Since, we have called this function with two arguments, it runs smoothly and we do not get any error.
这里,这个函数greet()有2个参数。
因此,我们可以调用带2个参数的函数,它顺利稳定的执行,我们没有获得任何错误。
If we call it with different number of arguments, the interpreter will complain. Below is a call to this function with one and no arguments along with their respective error messages.
>>> greet("Monica") # only one argument
TypeError: greet() missing 1 required positional argument: 'msg'
>>> greet() # no arguments
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'
如果用带不同数量参数去调用它,解释器会抱怨。下面调用这函数只带一个或不带参数关于他们各种的错误信息。
>>> greet("Monica") //带参数
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: greet() missing 1 required positional argument: 'msg'
>>> greet() //不带参数
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'
Variable Function Arguments
Up until now functions had fixed number of arguments. In Python there are other ways to define a function which can take variable number of arguments.
Three different forms of this type are described below.
变量函数参数
直到现在函数有固定参数数量。在python这里有另一个带可变数参数变量的方式定位一个函数。
3种不同形式的类型下面描述。
Python Default Arguments
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=). Here is an example.
def greet(name, msg = "Good morning!"):
"""
This function greets to
the person with the
provided message.
If message is not provided,
it defaults to "Good
morning!"
"""
print("Hello",name + ', ' + msg)
greet("Kate")
greet("Bruce","How do you do?")
In this function, the parameter name
does not have a default value and is required (mandatory) during a call.
On the other hand, the parameter msg
has a default value of "Good morning!"
. So, it is optional during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if we had defined the function header above as:
def greet(msg = "Good morning!", name):
We would get an error as:
SyntaxError: non-default argument follows default argument
默认参数
函数参数能有默认值在python中。
我们 提供一个默认值给一个参数,使用赋值操作符(=).这里有一个例子。
>>> def greet(name,msg = "Good morning!"):
... """
... This function greets to
... the person with the
... provided message.
...
... if message is not provided,
... it defaults to "Good
... morning!"
... """
... print("Hello",name + ',' + msg)
...
>>> greet("Kate")
Hello Kate,Good morning!
>>> greet("Bruce","How do you do?")
Hello Bruce,How do you do?
在这函数,这个参数name不带默认值, 在调用期间必须带上参数(强制性的)。
另一方面,这参数msg有默认参数"Good morning!",所以,它在调用期间是可选的带上参数的。如果一个值被提供给msg,它就会覆盖着默认值。
任何一个参数在函数可以有默认值。但是一旦我们有默认值,右边的所有的参数必须有默认值。
这意思是说,非默认参数不能跟随默认参数。例如,如果我们有定义这个函数头如下:
我们得到错误结果如下:
>>> def greet(msg = "Good morning!",name):
... pass
...
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
Python Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according to their position.
For example, in the above function greet()
, when we called it as greet("Bruce","How do you do?")
, the value "Bruce"
gets assigned to the argument name and similarly "How do you do?"
to msg.
Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. Following calls to the above function are all valid and produce the same result.
>>> # 2 keyword arguments
>>> greet(name = "Bruce",msg = "How do you do?")
>>> # 2 keyword arguments (out of order)
>>> greet(msg = "How do you do?",name = "Bruce")
>>> # 1 positional, 1 keyword argument
>>> greet("Bruce",msg = "How do you do?")
python 关键字参数
当我们调用带有某些值得函数,这些值获取根据它们的位置到赋给参数。
例如,在上面的greet()函数里,当我们调用它为greet("Bruce","How do you do?"),值"Bruce"赋值给参数name,同样的"How do you do?"付给msg。
Python 允许函数被使用关键字函数调用。当我们用这个方式调用函数时,这个参数的顺序(位置)可以被改变。以下调用上面的函数都是有效的,程序结果都是一样的。
In [1]: def greet(name,msg = "Good morning!"):
...: print("Hello",name + ',' + msg)
...:
#2 个关键字参数
In [2]: greet(name = "Bruce",msg = "How do you do ?")
Hello Bruce,How do you do ?
#2 个关键字参数(不按照参数顺序)
In [3]: greet(msg = "How do you do ?", name = "Bruce")
Hello Bruce,How do you do ?
#1 个位置参数,1 个关键字参数
In [4]: greet("Bruce",msg = "How do you do?")
Hello Bruce,How do you do?
As we can see, we can mix positional arguments with keyword arguments during a function call. But we must keep in mind that keyword arguments must follow positional arguments.
Having a positional argument after keyword arguments will result into errors. For example the function call as follows:
greet(name="Bruce","How do you do?")
Will result into error as:
SyntaxError: non-keyword arg after keyword arg
因此我们可以可看到, 一个函数调用期间我们能使用关键字参数打乱参数位置。但是我们必须记住关键字参数必须跟随位置参数。
有一个位置参数后面跟随关键字参数的结果将会错的。例如这函数调用为下面结果:
结果错误如下:
In [5]: greet(name = "Bruce","How do you do?")
File "<ipython-input-5-2dc5fade21f3>", line 1
greet(name = "Bruce","How do you do?")
^
SyntaxError: positional argument follows keyword argument
Python Arbitrary Arguments
Sometimes, we do not know in advance the number of arguments that will be passed into a function.Python allows us to handle this kind of situation through function calls with arbitrary number of arguments.
In the function definition we use an asterisk (*) before the parameter name to denote this kind of argument. Here is an example.
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello",name)
greet("Monica","Luke","Steve","John")
Output
Hello Monica
Hello Luke
Hello Steve
Hello John
Python 任意参数
有时候,我们不能知道在未来将传给函数参数的个数。Python允许我们操作这种情况,调用函数可以带任意个数的参数。
在这个函数定义中我们可以使用一个星号(*)在参数名之前去代表这种类型的参数。这里有一个例子。
In [9]: def greet(*names):
...: """ This function greets all
...: the person in the name tuple."""
...: for name in names:
...: print("Hell",name)
...:
In [10]: greet("Monica","Luke","Steve","John")
Hell Monica
Hell Luke
Hell Steve
Hell John
Here, we have called the function with multiple arguments. These arguments get wrapped up into a tuple before being passed into the function. Inside the function, we use a for
loop to retrieve all the arguments back.
这里,我们带多个参数调用这函数。这些参数在调用之前被封装成一个元组传到这函数里。函数内部,我们使用一个for循环来检索所有参数。
Check out these examples to learn more:
- PREVIOUS
PYTHON FUNCTIONS - NEXT
PYTHON RECURSION