目录
1. 函数的参数
函数可以接受多种类型的参数,包括位置参数、关键字参数和默认参数。
位置参数:
位置参数是最常见的参数类型,它们必须按照定义时的顺序传递给函数。
def greet(name, message):
print(f"{message}, {name}!")
greet("Alice", "Hello") # 输出:Hello, Alice!
关键字参数:
关键字参数允许在调用函数时指定参数名,参数的顺序可以与定义时不同。
greet(name="Alice", message="Hello") # 输出:Hello, Alice!
greet(message="Hi", name="Bob") # 输出:Hi, Bob!
默认参数:
默认参数在定义函数时指定默认值,如果调用时未传递该参数,则使用默认值。
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # 输出:Hello, Alice!
greet("Bob", "Hi") # 输出:Hi, Bob!
2. 关键字参数
关键字参数的使用使得函数调用更加灵活和清晰,尤其是当函数有多个参数时。
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
describe_pet(animal_type="dog", pet_name="Rex") # 输出:I have a dog named Rex.
describe_pet(pet_name="Whiskers", animal_type="cat") # 输出:I have a cat named Whiskers.
使用关键字参数可以使代码更具可读性,因为每个参数的意义都显而易见。
3. 参数组
Python提供了 *args
和 **kwargs
来处理不定长参数。
*args
: *args
接收任意数量的位置参数,传递给函数时以元组的形式存在。
def make_pizza(size, *toppings):
print(f"Making a {size} inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(12, "pepperoni", "mushrooms", "green peppers")
# 输出:
# Making a 12 inch pizza with the following toppings:
# - pepperoni
# - mushrooms
# - green peppers
**kwargs
:
**kwargs
接收任意数量的关键字参数,传递给函数时以字典的形式存在。
def build_profile(first, last, **user_info):
profile = {
"first_name": first,
"last_name": last
}
profile.update(user_info)
return profile
user_profile = build_profile("Albert", "Einstein", location="Princeton", field="Physics")
print(user_profile)
# 输出:
# {'first_name': 'Albert', 'last_name': 'Einstein', 'location': 'Princeton', 'field': 'Physics'}