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

Python编写Employee类调用is_higher_rank方法触发AssertionError求助

代码问题梳理

    1. 类方法缩进错误:is_higher_rank、__eq__、__repr__三个方法定义时没有缩进在Employee类的代码块内,不属于类的成员方法,实例无法正常调用对应方法。
    1. 参数名引用错误:is_higher_rank方法定义的第二个入参名为Employee,但方法内部错误引用了不存在的变量Employee2,导致逻辑执行异常。
    1. 命名规范问题:不要直接用类名Employee作为参数名,容易和类本身混淆,建议修改为语义更清晰的名称。

修改后的完整代码

class Employee:
    def __init__(self, name, age, rank_ID):
        self.name = name
        self.age = age
        self.rank_ID = rank_ID

    def is_higher_rank(self, other_employee):
        if self.__eq__(other_employee) == True:
            return "These employees are both the same rank!"
        elif self.rank_ID < other_employee.rank_ID:
            return self.name + " is senior in rank than " + other_employee.name + "!"
        else:
            return other_employee.name + " is senior in rank than " + self.name + "!"

    def __eq__(self, other_employee):
        return self.rank_ID == other_employee.rank_ID

    def __repr__(self):
        rep = ("Employee Name: " + str(self.name) + "\n" + "Age: " + str(self.age) + "\n" + "ID: "
               + str(self.rank_ID) + "\n")
        return rep


Employee1 = Employee("Michael", 45, 12345)
Employee2 = Employee("Dwight", 40, 23456)
Employee3 = Employee("Pam", 30, 34567)
Employee4 = Employee("Jim", 35, 12345)


def test_is_higher_rank():
    assert Employee1.is_higher_rank(Employee4) == 'These employees are both the same rank!', "Should be the same"
    assert Employee3.is_higher_rank(Employee2) == 'Dwight is senior in rank than Pam!', \
        "Should be the Dwight senior Pam"
    assert Employee4.is_higher_rank(Employee2) == 'Jim is senior in rank than Dwight!', \
        "Should be Jim senior Dwight"
    assert Employee4.is_higher_rank(Employee3) == 'Jim is senior in rank than Pam!', \
        "Should be Jim senior Pam"


print()
print(Employee1)
print(Employee2)
print(Employee3)
print(Employee4)
print(Employee1.is_higher_rank(Employee4))
print(Employee3.is_higher_rank(Employee2))
print(Employee4.is_higher_rank(Employee2))
print(Employee4.is_higher_rank(Employee3))
print()

test_is_higher_rank()
print("Everything Passed.")
print()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:36:03