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

Python类实例成员异常共享:调用单个实例方法却更新所有实例

问题分析与解决方案

问题根源

你定义的File类中,__name、__pos_in_list、__statements、__matches都是类属性(直接在类体中定义,未通过self.绑定到实例)。类属性属于整个类,会被所有该类的实例共享,所以当你调用A[0].set_matches(...)时,实际修改的是类级别的__matches列表,所有File实例都会同步看到这个变化。

修复代码

将类属性改为实例属性,在__init__方法中初始化每个实例独有的属性:

@dataclass
class Match:
    length: int
    pos_A: int
    pos_B: int
    f_index: int

class File:
    def __init__(self, name: str, pos: int, statements: list[Statement]):
        # 每个实例独立拥有自己的属性副本
        self.__name = name
        self.__pos_in_list = pos
        self.__statements = statements
        self.__matches = []  # 每个实例初始化时创建专属空列表
   
    def set_matches(self, match: Match):
        # 修正参数类型标注:传入单个Match实例时,类型应为Match而非列表
        self.__matches.append(match)

额外说明

原set_matches方法的参数标注写为[Match](列表类型),但你调用时传入的是单个Match实例,这里需要统一:

  • 若添加单个匹配项,保持append用法,参数类型改为Match;
  • 若批量添加多个匹配项,将方法改为self.__matches.extend(matches),参数类型用list[Match]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:10:39