代码之家  ›  专栏  ›  技术社区  ›  Mark

实现抽象类

  •  0
  • Mark  · 技术社区  · 5 月前

    我是Python编码的初学者,我尝试学习抽象类。我在实现两个扩展抽象类考试的考试时遇到了问题,这两个考试定义了诊断测试的契约。

    class Person:
    def __init__(self, name: str, age: int):
    self.name = name
    self.age = age
    
    class Patient(Person):
    def __init__(self, name: str, age: int, id: str, symptoms: list\[str\], cholesterol: float, iron_level: float):
    super().__init__(name, age)
    self.id = id
    self.symptoms = symptoms
    self.cholesterol = cholesterol
    self.iron_level = iron_level\`
    
    class CholesterolExam(Exam):
    def __init__(self):
    super().__init__('Cholesterol Exam')
    
        def perform_exam(self,cholesterol_exam):
            if cholesterol_exam >= 200:
                return False
            return True
    
    class IronLevelExam(Exam):
    def __init__(self):
    super().__init__('Iron Exam')
    
        def perform_exam(self,iron_level_exam):
            if iron_level_exam>50 and iron_level_exam<170:
                return True    
    
    class Test03(unittest.TestCase):
        def test_doctor(self):
            cholesterol_exam = CholesterolExam()
            iron_level_exam = IronLevelExam()
            p = Patient('John', 30, '001', ['cough', 'fever'], 180, 300)
            cholesterol_exam_result, iron_exam_result = [exam.perform_exam(p) for exam in [cholesterol_exam, iron_level_exam]]
    
            self.assertTrue(cholesterol_exam_result)
            self.assertFalse(iron_exam_result)
    
    test(Test03)
    

    我收到错误消息:

    test_doctor中的第32行 胆固醇检查结果,铁水平检查结果=[胆固醇检查中的检查性能检查(p)]

    第12行,执行考试 如果胆固醇检查>=200:

    类型错误:“>=”“Patient”和“int”的实例之间不支持

    1 回复  |  直到 5 月前
        1
  •  0
  •   Mario Mateaș    5 月前

    您正在比较 Patient 对象与 200 ,这是一个 Integer ,但您应该将该数字与之进行比较的实际内容可能是 p .

    您有两个选择:

    1. 要么打电话 exam.perform_exam 另一个参数类似于int,例如 p.cholesterol
    2. 假设 考试 需要a 病人 ,将参数中的整数字段与该字段进行比较 200 .

    这不是关于抽象类,而是关于Python缺乏类型推理。

    上述第一种情况的一个例子:

    cholesterol_exam_result, iron_exam_result = [exam.perform_exam(p.cholesterol) for exam in [cholesterol_exam, iron_level_exam]]