如何在Python类

时间:2015-11-10 12:17:03

标签: python python-2.7 class oop

class NewClass:

    def __init__(self, a):
        self.a = a

    def __contains__(self, item):

        # ???

如何编写# ???以启用:

x in list_of_NewClassObject

并返回TrueFalse

1 个答案:

答案 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