Python函数参数

Python函数参数

Python函数参数

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

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") # 只有一个参数
TypeError: greet() missing 1 required positional argument: 'msg'
>>> greet() # 没有参数
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'

Python函数参数类型

Python函数参数类型

  到目前为止,函数有固定数量的参数。在 Python 中,还有其他方法可以定义可以接受可变数量参数的函数。以下是参数的三种不同形式。

Python 默认参数

  函数参数在 Python 中可以有默认值。我们可以使用赋值运算符 (=) 为参数提供默认值。

def greet(name, msg="Good morning!"):
    """
    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(),当我们将它称为 as 时greet("Bruce", "How do you do?"),值"Bruce"会被分配给参数名称类似地"How do you do?"

  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 允许我们通过带有任意数量参数的函数调用来处理这种情况。

  在函数定义中,我们在参数名称前使用星号 (*) 来表示此类参数。更多Python任意参数可参考官网

def fav_blog(*names):
    """This function greets all
    the person in the names tuple."""

    # names is a tuple with arguments
    for name in names:
        print("My Favourite blog is", name)


greet("晓得博客", "WordPress建站", "Astra Pro教程", "WordPress外贸建站")

输出


My Favourite blog is 晓得博客
My Favourite blog is WordPress建站
My Favourite blog is Astra Pro教程
My Favourite blog is WordPress外贸建站

  在这里,我们使用多个参数调用了该函数。这些参数在传递到函数之前被包装成一个元组。在函数内部,我们使用一个for循环来检索所有参数。

  推荐:零基础如何开始学习Python

5/5 - (1 vote)

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python函数参数

转载请保留链接:https://www.pythonthree.com/python-function-argument/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部