我的指示是返回True如果student_id数据的是彼此相等,则为true;如果名字是彼此相等。我相信,我现在用的是“其他”部分错误,我已经看了它,一直没能解决这个问题
这是我的代码
def __eq__(self, other):
if self.student_id == self.student_id:
return True
elif self.name == self.name:
return False
这是它的返回错误
AssertionError: <src.student.Student object at 0x039C1490> == <src.student.Student object at 0x039C1650> : Student [Captain Chris, 00001960, Computer Engineering, 0.00 F] and [Captain Chris, 00001961, Computer Engineering, 0.00 F] are not equal.
您正在测试,如果self.student_id
等于iself。你应该测试,如果你的当前对象的student_id
变量(即self
)等于其他student_id
self.student_id == other.student_id
虽然,是你一定要了解你在做什么吗?你基本上测试此:
也许你的意思做:
def __eq__(self, other):
if self.student_id == other.student_id:
return True
elif self.name == other.name:
return True
else:
return False
这可能是高高兴兴地简化为:
def __eq__(self, other):
return self.student_id == other.student_id or self.name == other.name
做这样的事情:
class student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
def __eq__(self, other):
status = False
if self.student_id == other.student_id:
status = True
return status
s1 = student("Davidd", 10)
s2 = student("David", 11)
print(s1 == s2)
假
s1 = student("David", 10)
s2 = student("David", 11)
print(s1 == s2)
假
s1 = student("David", 11)
s2 = student("David", 11)
print(s1 == s2)
真正
s1 = student("David", 101)
s2 = student("Davids", 101)
print(s1 == s2)
真正