class NewClass:
def __init__(self, a):
self.a = a
def __contains__(self, item):
# ???
如何编写# ???
以启用:
x in list_of_NewClassObject
并返回True
或False
。
答案 0 :(得分:2)
正如@PeterWood所指出的,你可能想要定义__eq__
而不是:
class NewClass(object):
def __init__(self, a):
self.a = a
def __eq__(self, item):
if isinstance(item, NewClass):
return self.a == item.a
return object.__eq__(self, item)
def __ne__(self, item):
return not self.__eq__(item)
def __hash__(self):
return hash(self.a)
示例:
>>> a = NewClass(1)
>>> b = NewClass(2)
>>> x = NewClass(1)
>>> x in [a, b]
True