例如,我有一个自定义类,如下所示:
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__
,但没能达到我的目的。你知道吗
我想这就是你想要的(假设你用
self.alarmId
来竞争):结果是:
根据您的问题,我认为您正在为列表寻找conditionall
append()
函数。这将是如下所示:您可以使用此功能将警报添加到列表中,并立即检查警报是否在列表中。这显然不是一个重载函数或运算符,但它应该可以工作。你知道吗
希望有帮助。你知道吗
编辑: 可以使用要添加到的列表和要添加的项调用函数。如果该项是否已添加,则返回布尔标志。你知道吗
相关问题 更多 >
编程相关推荐