我需要覆盖哪个操作符来检查列表中是否存在自定义对象?

2024-09-30 01:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一个自定义类,如下所示:

 class Alarm(object):
        def __init__(self, alarmId, msg):
            self.alarmId = alarmId
            self.msg = msg

        def __eq__(self, other):
            return self.alarmId == other.alarmId

    aList = list()
    a = Alarm(1, "hello")
    b = Alarm(1, "good")
    aList.append(a)
    aList.append(b)

具有相同Id的报警被认为是相同的,因此“a”和“b”实际上是相同的。我想检查列表中是否已经存在相同的报警,如果已经存在,则无需将其添加到列表中。你知道吗

if a in aList: # I wish when this "in" called, I could call one member function of a to match the whole list
   pass 

但我需要覆盖哪个函数才能完成此操作?我试过__eq__,但没能达到我的目的。你知道吗


Tags: inself报警列表objectdefmsglist
2条回答

我想这就是你想要的(假设你用self.alarmId来竞争):

class Alarm(object):
    def __init__(self, alarmId, msg):
        self.alarmId = alarmId
        self.msg = msg

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
            and self.alarmId == other.alarmId)


aList = list()
a = Alarm(1, "hello")
b = Alarm(2, "good")
aList.append(a)
aList.append(b)

if a in aList:
    print("a found")

c = Alarm(3, "good")

if c not in aList:
    print("c not found")

结果是:

a found
c not found

根据您的问题,我认为您正在为列表寻找conditionallappend()函数。这将是如下所示:

def listadd(list, toadd):
    for alarm in list:
        if alarm == toadd:
            return false

    list.append(toadd)
    return true

您可以使用此功能将警报添加到列表中,并立即检查警报是否在列表中。这显然不是一个重载函数或运算符,但它应该可以工作。你知道吗

希望有帮助。你知道吗

编辑: 可以使用要添加到的列表和要添加的项调用函数。如果该项是否已添加,则返回布尔标志。你知道吗

相关问题 更多 >

    热门问题