http://mobi.cqfowei.com
http://cctv.cqfowei.com
http://nab.cqfowei.com
http://zhongchao.cqfowei.com
http://yijia.cqfowei.com
在Python中,函数可以定义带有默认值的参数,称为默认参数。当调用函数时没有提供这些参数的值,就会使用默认值。
def greet(name, message="Hello"): print(f"{message}, {name}!") # 使用默认参数 greet("Alice") # 输出: Hello, Alice! # 覆盖默认参数 greet("Bob", "Good morning") # 输出: Good morning, Bob!
Python在函数定义时计算默认参数的值,而不是每次调用时重新计算。这会导致一个常见陷阱:当默认参数是可变对象(如列表、字典)时,所有调用会共享同一个对象。
问题代码示例:
def append_to(element, items=[]): items.append(element) return items print(append_to(1)) # 输出: [1] print(append_to(2)) # 输出: [1, 2] 而不是预期的 [2]!
正确解决方法:
def append_to(element, items=None): if items is None: items = [] items.append(element) return items print(append_to(1)) # 输出: [1] print(append_to(2)) # 输出: [2]
在函数定义中,默认参数必须位于非默认参数之后。Python函数参数顺序为:位置参数、默认参数、可变位置参数(*args)、关键字参数、可变关键字参数(**kwargs)。
# 正确的顺序 def correct_func(a, b="default", *args, **kwargs): pass # 错误的顺序 - 会导致语法错误 def incorrect_func(a="default", b): # SyntaxError pass
• 避免使用可变对象作为默认值(列表、字典、集合等) • 使用None作为默认值,然后在函数内部创建可变对象 • 默认参数应该是不变对象(数字、字符串、元组等) • 对于复杂默认值,使用None并添加文档说明
def get_default(): return "Default Value" def my_function(param=get_default()): print(param) my_function() # 输出: Default Value
class MyClass: def __init__(self): self.value = "Initial" def modify_obj(obj=MyClass()): obj.value = "Modified" return obj first = modify_obj() print(first.value) # 输出: Modified second = modify_obj() print(second.value) # 输出: Modified (但使用的是同一个对象!) print(first is second) # 输出: True
1. 默认参数在函数定义时计算一次,而不是每次调用时计算
2. 避免使用可变对象作为默认参数值
3. 使用None作为默认值并在函数内初始化可变对象
4. 默认参数必须放在非默认参数之后
5. 对于复杂默认值,考虑使用None并添加文档说明
6. 类实例作为默认参数也会共享同一个实例
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。