在Python中设置函数参数可以通过以下几种方式:
基本参数
定义函数时,参数列表中的每个参数都应该用逗号分隔。
调用函数时,需要按照函数定义中的顺序提供参数。
默认参数值
为参数设置默认值,这样在调用函数时如果没有提供该参数,将使用默认值。
语法格式:`形参名 = 默认值`。
示例:
def greet(name, greeting="Hello"):print(greeting, name)greet("Alice") 输出 "Hello Alice"greet("Bob", "Hi") 输出 "Hi Bob"
关键字参数
调用函数时,可以使用关键字参数,即参数名=值的形式。
示例:
def greet(name, greeting="Hello"):print(greeting, name)greet(greeting="Hi", name="Bob") 输出 "Hi Bob"

强制关键字参数
带有 `*` 的参数必须以关键字形式传递。
示例:
def describe_pet(pet_name, *, animal_type="dog", age=None):description = f"I have a {animal_type} named {pet_name}"if age is not None:description += f", and it is {age} years old."return description
可变参数
使用 `*args` 接收任意数量的位置参数,使用 ` kwargs` 接收任意数量的关键字参数。
示例:
def func(*args, kwargs):for arg in args:print(f"Positional argument: {arg}")for key, value in kwargs.items():print(f"Keyword argument: {key} = {value}")
参数顺序
当函数有多个参数时,如果你想给部分参数提供默认参数,那么这些参数必须在参数的末尾。
示例:
def func(a, b, c=0, d=0):return a + b + c + d
以上是Python中设置函数参数的基本方法。
