Python编写Employee类调用is_higher_rank方法触发AssertionError求助
代码问题梳理
- 类方法缩进错误:
is_higher_rank、__eq__、__repr__三个方法定义时没有缩进在Employee类的代码块内,不属于类的成员方法,实例无法正常调用对应方法。
- 类方法缩进错误:
- 参数名引用错误:
is_higher_rank方法定义的第二个入参名为Employee,但方法内部错误引用了不存在的变量Employee2,导致逻辑执行异常。
- 参数名引用错误:
- 命名规范问题:不要直接用类名
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
相关产品推荐
相关产品推荐

