You need to enable JavaScript to run this app. Python数据类如何将Owner实例传入HallOfFame类完成添加操作
优惠活动
大模型
产品
解决方案
定价
更多

Python数据类如何将Owner实例传入HallOfFame类完成添加操作

问题原因

你的代码存在2个核心错误:

  1. HallOfFame 数据类的字段设计不符合需求:
    • 多余定义了不需要的owner字段,实例化时必须强制传入
    • 名人堂列表hall_of_fame没有设置默认值,实例化时也需要强制传入,且可变类型默认值不能直接赋值为空列表,会出现所有实例共享同一个列表的隐患
  2. add方法实现错误:append是列表对象的方法,不能直接调用self.append,需要操作类内部的hall_of_fame列表属性

完整修改后的代码

from dataclasses import dataclass, field
from typing import List


@dataclass
class Owner:
    name: str
    qty_of_belongings: int

    def __eq__(self, other):
        # 新增类型判断,避免和非Owner实例比较时报错
        if not isinstance(other, Owner):
            return False
        return self.qty_of_belongings == other.qty_of_belongings

    def __str__(self):
        return f"{self.name}: {self.qty_of_belongings}"


@dataclass
class HallOfFame:
    # 移除多余的owner字段,给名人堂列表设置默认空列表
    hall_of_fame: List[Owner] = field(default_factory=list)

    def add(self, owner: Owner):
        # 操作内部的hall_of_fame列表执行添加
        self.hall_of_fame.append(owner)


# 测试代码
o1 = Owner("Grace", 5)
o2 = Owner("Sharon", 3)
hof = HallOfFame()
hof.add(o1)
hof.add(o2)

# 验证结果
for owner in hof.hall_of_fame:
    print(owner)

运行效果

执行测试代码后会输出:

Grace: 5
Sharon: 3

完全符合预期功能要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 19:15:04