来源
http://cctv5.hlkjfj.com
http://tv3.hlkjfj.com
http://tv2.hlkjfj.com
http://tv1.hlkjfj.com
http://hlkjfj.com
在Python中,函数参数的传递方式决定了如何将数据传递给函数。理解不同的参数传递方式能让你编写更灵活、可读性更强的代码。
最常见的参数传递方式,参数按顺序依次传递
通过参数名指定值,提高代码可读性
为参数提供默认值,调用时可省略
位置参数是最基本的参数传递方式,按照函数定义时参数的顺序传递值。
def greet(name, greeting):
print(f"{greeting}, {name}!")
# 使用位置参数调用
greet("Alice", "Hello") # 输出: Hello, Alice!
greet("Bob", "Hi") # 输出: Hi, Bob!
关键字参数通过参数名指定值,使代码更易读,且不必记住参数顺序。
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
# 使用关键字参数调用
describe_pet(animal_type="hamster", pet_name="Harry")
describe_pet(pet_name="Whiskers", animal_type="cat")
默认参数允许为函数参数提供默认值,调用时可省略这些参数。
def make_shirt(size="large", message="I love Python"):
print(f"制作一件{size}号T恤,印有: '{message}'")
# 使用默认参数
make_shirt() # 使用所有默认值
make_shirt(size="medium") # 修改size,message使用默认值
make_shirt("small", "Hello World!") # 位置参数
当不确定要传递多少参数时,可以使用可变参数。
收集所有位置参数到一个元组
def sum_numbers(*args):
total = 0
for num in args:
total += num
return total
print(sum_numbers(1, 2, 3)) # 输出: 6
print(sum_numbers(4, 5, 6, 7)) # 输出: 22
收集所有关键字参数到一个字典
def build_profile(**kwargs):
profile = {}
for key, value in kwargs.items():
profile[key] = value
return profile
user = build_profile(name="Alice", age=30, occupation="Engineer")
print(user) # 输出: {'name': 'Alice', 'age': 30, 'occupation': 'Engineer'}
在函数定义中,参数顺序必须遵循:
def complex_function(a, b=2, *args, c=3, **kwargs):
print(f"a={a}, b={b}, c={c}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
complex_function(1, 4, 5, 6, c=7, d=8, e=9)
Python中的参数传递既不是值传递也不是引用传递,而是"对象引用传递"。
数字、字符串、元组等不可变对象在函数内修改会创建新对象
def modify_number(x):
x = x + 10
print("函数内:", x)
num = 5
modify_number(num)
print("函数外:", num) # 输出: 5 (未改变)
列表、字典等可变对象在函数内修改会影响原始对象
def modify_list(lst):
lst.append(4)
print("函数内:", lst)
my_list = [1, 2, 3]
modify_list(my_list)
print("函数外:", my_list) # 输出: [1, 2, 3, 4] (已改变)
灵活运用位置参数、关键字参数、默认参数和可变参数,将使你的Python函数更加强大和灵活。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。