Python不要使用可变对象作为函数的默认参数

中一个常见的陷阱,与可变默认参数有关。

让我们看看AutoParamGroup类的__init__方法定义:

python 复制代码
def __init__(self, ref_mode=[], ref_value=[], ref_group_num=[], ref_interp_method=[], ref_gain_lux=0,
             param_list=[]):
    self.ref_mode = ref_mode
    self.ref_value = ref_value
    self.ref_group_num = ref_group_num
    self.ref_interp_method = ref_interp_method
    self.ref_gain_lux = ref_gain_lux
    self.param_list = param_list

这里的问题在于使用了可变对象(列表[])作为默认参数值。在Python中,默认参数值是在函数定义时就被创建的,而不是在函数调用时。这意味着所有使用默认参数的实例都会共享同一个列表对象。

要解决这个问题,推荐的做法是使用None作为默认值,然后在__init__方法中创建新的列表。以下是修正后的代码:

python 复制代码
def __init__(self, ref_mode=None, ref_value=None, ref_group_num=None, ref_interp_method=None, 
             ref_gain_lux=0, param_list=None):
    self.ref_mode = ref_mode if ref_mode is not None else []
    self.ref_value = ref_value if ref_value is not None else []
    self.ref_group_num = ref_group_num if ref_group_num is not None else []
    self.ref_interp_method = ref_interp_method if ref_interp_method is not None else []
    self.ref_gain_lux = ref_gain_lux
    self.param_list = param_list if param_list is not None else []

这样修改后:

  1. 每次创建新实例时都会创建新的列表对象
  2. 不同实例之间的列表将是独立的
  3. 不会出现数据残留的问题

这是Python中的一个经典问题,在使用可变对象(如列表、字典等)作为默认参数时经常会遇到。记住:永远不要使用可变对象作为函数的默认参数

相关推荐
IVEN_14 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang15 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮16 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling16 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮19 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽19 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers