【发布时间】:2022-01-18 10:37:29
【问题描述】:
我有 3 个课程:
Person, Teacher(Person) 和 Student(Person) 我需要比较它的对象。
我在做什么:
class Student(Person):
def __init__(self, name, year_of_birth, age):
super().__init__(name, year_of_birth, age)
self.skill= skill
def __eq__(self, st1):
if self.age == st1.age:
return True
return False
def __lt__(self, st1):
if self.age < st1.age:
return True
return False
def __gt__(self, st1):
if self.age > st1. age:
return True
return False
在'Teacher(Person)' 类中的相同动作通过他们多年的经验来比较老师。 现在我想比较“学生”和“教师”类的对象
student1 == teacher1
我应该得到“错误”,因为它们无法比较(学生按年龄比较,教师按经验比较)
我正在我的“人”类中尝试这个:
def __eq__(self, person2):
if self.__class__.__name__ == person2.__class__.__name__:
return True
return False
但是当我调用 'print(student1 == teacher2)' 时,我得到了
Traceback (most recent call last):
File "C:\Users\User1\PycharmProjects\university\main.py", line 95, in <module>
print(student1 == teacher2)
File "C:\Users\User1\PycharmProjects\university\main.py", line 71, in __eq__
if self.years_of_experience == teacher2.years_of_experience:
AttributeError: 'Student' object has no attribute 'years_of_experience'
任何建议如何正确比较这两个对象并得到 False,因为它们是不同类的对象并且无法比较(根据我的任务)?
【问题讨论】:
-
检查
Student.__eq__和Teacher.__eq__中第二个参数的类型。 -
Person.__eq__如果在子类中覆盖它,则不会被调用,除非你通过super().__eq__(other)显式调用它... -
那么我是否理解正确,我不需要在我的
Person类中覆盖__eq__?我必须检查我的Student和Teacher类的__eq__方法中的类,对吧? -
您可以在
Person.__eq__中查看通用类,然后在子类中进行更具体的附加检查;但同样,您也需要显式调用Person.__eq__。类似return super().__eq__(other) and self... == other..。 -
非常感谢!我从
Person类中删除了__eq__,并为Teacher和Student类中的重写方法添加了一些逻辑。感谢您的提示!
标签: python inheritance operators comparison-operators