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

Python3.9 Command类多实例初始化属性互相干扰问题排查

问题根因

你遇到的实例互相干扰问题核心是Command类的属性定义错误:input_resources、output_resources被定义为了类属性而非实例属性。
Python中字典属于可变对象,作为类属性定义时,所有类实例会共享同一个字典对象。你在__init__方法中修改这两个字典的操作,会作用到所有已创建的实例上,这就是为什么创建第二个实例后,第一个实例的资源列表会被篡改、两个实例能拿到相同内存地址的资源对象。

修复方案

将两个字典的初始化逻辑从类定义层级移到__init__方法内部,确保每个实例都有独立的资源字典:

class Command:
    """
    Contains a ratio for exchanging input resources into output resources
    """

    name: str
    # 移除类层级的字典定义
    # input_resources: dict[str, type(Resource)] = {}
    # output_resources: dict[str, type(Resource)] = {}

    def __init__(self, name: str,
                 input_resources: dict[str, type(Resource)], output_resources: dict[str, type(Resource)]):
        self.name: str = name
        # 每个实例初始化单独创建空字典
        self.input_resources: dict[str, type(Resource)] = {}
        self.output_resources: dict[str, type(Resource)] = {}

        for input_resource_name, input_resource in input_resources.items():
            self.input_resources[input_resource_name]: type(Resource) = input_resource.copy()

        for output_resource_name, output_resource in output_resources.items():
            self.output_resources[output_resource_name]: type(Resource) = output_resource.copy()
    
    # 其余方法保持原有逻辑不变

修改完成后,每个实例的资源字典独立,创建新实例不会再影响已有的旧实例属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:15:06