Python代码 在线执行

Python 函数参数

/function-argument

在 Python 中,您可以定义一个带有可变数量参数的函数。 在本文中,您将学习使用默认,关键字和任意参数定义此类函数。

参数

用户定义的函数主题中,我们学习了有关定义和调用函数的知识。 否则,函数调用将导致错误。 这是一个例子。

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!

在此,函数greet()具有两个参数。

由于我们已经使用两个参数调用了此函数,因此该函数运行平稳,并且没有任何错误。

如果使用不同数量的参数调用它,则解释器将显示错误消息。 下面是对此函数的调用,其中包含一个参数,没有参数以及它们各自的错误消息。

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

可变函数参数

到目前为止,函数具有固定数量的参数。 在 Python 中,还有其他方法来定义可以采用可变数量的参数的函数。

下面介绍这种类型的三种不同形式。

Python 默认参数

函数参数在 Python 中可以具有默认值。

我们可以使用赋值运算符(=)为参数提供默认值。 这是一个例子。

def greet(name, msg="Good morning!"):
    """
    This function greets to
    the person with the
    provided message.

    If the message is not provided,
    it defaults to "Good
    morning!"
    """

    print("Hello", name + ', ' + msg)

greet("Kate")
greet("Bruce", "How do you do?")

输出

Hello Kate, Good morning!
Hello Bruce, How do you do?

在此函数中,参数name没有默认值,并且在通话期间是必需的(强制性的)。

另一方面,参数msg的默认值为"Good morning!"。 因此,在通话期间它是可选的。 如果提供了一个值,它将覆盖默认值。

函数中的任意数量的参数都可以具有默认值。 但是,一旦有了默认参数,它右边的所有参数也必须具有默认值。

这意味着非默认参数不能跟随默认参数。 例如,如果我们将上面的函数头定义为:

def greet(msg = "Good morning!", name):

我们将收到以下错误消息:

SyntaxError: non-default argument follows default argument

Python 关键字参数

当我们调用带有某些值的函数时,这些值将根据其位置分配给参数。

例如,在上面的函数greet()中,当我们将其称为greet("Bruce", "How do you do?")时,会将值"Bruce"分配给参数name,并且将"How do you do?"分配给msg

Python 允许使用关键字参数调用函数。 当我们以这种方式调用函数时,参数的顺序(位置)可以更改。 对上述函数的后续调用均有效,并产生相同的结果。

# 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?") 

如我们所见,我们可以在函数调用期间将位置参数与关键字参数混合。 但是我们必须记住,关键字参数必须跟随位置参数。

在关键字参数之后放置位置参数会导致错误。 例如,函数调用如下:

greet(name="Bruce","How do you do?")

会导致错误:

SyntaxError: non-keyword arg after keyword arg

Python 任意参数

有时,我们事先不知道将传递给函数的参数数量。 Python 允许我们通过带有任意数量参数的函数调用来处理这种情况。

在函数定义中,我们在参数名称前使用星号(*)表示此类参数。 这是一个例子。

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

输出

Hello Monica
Hello Luke
Hello Steve
Hello John

在这里,我们调用了带有多个参数的函数。 这些参数在传递给函数之前被包装为一个元组。 在函数内部,我们使用for循环取回所有参数。