什么是在Python __eq __(其他)正确的语法

问题描述 投票:-1回答:2

我的指示是返回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.
python
2个回答
0
投票

您正在测试,如果self.student_id等于iself。你应该测试,如果你的当前对象的student_id变量(即self)等于其他student_id

self.student_id == other.student_id

虽然,是你一定要了解你在做什么吗?你基本上测试此:

  • 如果student_id数据等于其他的student_id数据:等于为True
  • 但是,如果他们不相等的,如果他们的名字是相同的:平等是假的(???)。
  • 最后:如果他们的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

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)

真正

© www.soinside.com 2019 - 2024. All rights reserved.