我的指令是,如果student_id彼此相等,则返回True;如果名称彼此相等,则返回False。我相信我在错误地使用了“其他”部分,并且已经查找并无法解决它
这是我的代码
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.
答案 0 :(得分:0)
您正在测试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
答案 1 :(得分:0)
执行以下操作:
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)
是