You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Feature类实例默认参数复用导致数据污染问题求助

问题分析与解决方案

问题根源

Python里,可变默认参数(比如list=[], dict={})是在函数定义的时候就创建好了,不是每次调用__init__都会重新生成。这就导致所有Feature实例会共用同一个默认的coordinates列表、properties字典和dictionary字典。当第一个实例通过gen_grid_adv修改了这些数据后,后面创建的实例用的还是被修改过的同一个对象,自然就串数据了——哪怕两个实例内存地址不一样,它们用的默认可变参数是同一个引用。

修复代码

把__init__的可变默认参数改成None,然后在方法内部初始化空的可变对象:

class Feature:
    def __init__(self, featuretype: str="Point", coordinates: list=None, 
                 properties: dict=None, dictionary: dict=None):
        # 给没传值的参数初始化独立的空对象
        coordinates = coordinates if coordinates is not None else []
        properties = properties if properties is not None else {}
        dictionary = dictionary if dictionary is not None else {}
        
        # 保留你原来的逻辑
        if dictionary:
            self.dict = dictionary
        else:
            self.new(featuretype, coordinates, properties)
        self.update()

原理说明

每次调用__init__时,如果没传coordinates、properties或dictionary,就会在方法内部新建一个空列表/字典,这样每个Feature实例都拥有完全独立的可变对象,再也不会出现数据互相污染的情况。

内容的提问来源于stack exchange,提问作者Ben Kraas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 09:57:29