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

抽象类的实现问题求助

抽象类的实现问题求助

看了你的代码和报错信息,问题的核心非常明确——你调用perform_exam时传入的是整个Patient对象,但你的perform_exam方法却期望接收单个的数值(胆固醇或铁含量),这直接导致了类型错误:Python没法把Patient实例和整数做大小比较。

下面一步步帮你修正问题:

1. 修正perform_exam的参数与逻辑

两个Exam子类的perform_exam方法应该接收Patient对象,然后从对象中取出对应的属性进行判断;另外IronLevelExam的方法之前没有处理不符合条件的情况,会默认返回None,这在测试断言时会出问题,必须补上明确的返回值:

class CholesterolExam(Exam):
    def __init__(self):
        super().__init__('Cholesterol Exam')

    # 改为接收Patient对象,取出对应的cholesterol属性做判断
    def perform_exam(self, patient):
        if patient.cholesterol >= 200:
            return False
        return True

class IronLevelExam(Exam):
    def __init__(self):
        super().__init__('Iron Exam')

    # 接收Patient对象,取出iron_level,同时补上不符合条件的返回逻辑
    def perform_exam(self, patient):
        if 50 < patient.iron_level < 170:
            return True
        # 不符合范围时明确返回False,避免返回None
        return False

2. 补全抽象类Exam的正确定义

你没有贴出抽象类Exam的代码,这里给你补全标准的抽象类实现(需要用到abc模块),确保所有子类都遵循统一的方法签名:

from abc import ABC, abstractmethod

class Exam(ABC):
    def __init__(self, name: str):
        self.name = name

    # 定义抽象方法,强制子类实现,同时约束参数和返回值类型
    @abstractmethod
    def perform_exam(self, patient: Patient) -> bool:
        pass

3. 验证测试用例的逻辑

你的测试用例逻辑是对的:

  • 患者John的胆固醇值180(<200,CholesterolExam应返回True)
  • 铁含量300(超出50-170的正常范围,IronLevelExam应返回False)

修正完方法后,列表推导式[exam.perform_exam(p) for exam in [cholesterol_exam, iron_level_exam]]就能正确传递Patient对象,取出对应属性完成判断,测试用例可以正常通过。

备注:内容来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:22:59