0

I have written a python class that overrides eq and neq. I am used to obtaining a list of unique elements in a sequence seq using

unique_element_list = list(set(seq))

This does not seem to work for lists containing instances of my class, and I do not know why.

Following the recommendation here, Elegant ways to support equivalence ("equality") in Python classes, I have written my class as follows:

class MyObject(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.__dict__ == other.__dict__
        else:
            return False

    def __ne__(self, other):
        return not self.__eq__(other)

Now here are three instances of this class:

obj1 = MyObject(1, 2)
obj2 = MyObject(3, 4)
obj3 = MyObject(1, 2)

obj1 == obj2 
False 

obj1 == obj3 
True 

Ok, so far so good. But now:

obj_list = [obj1, obj2, obj3]
len(obj_list)
3
len(set(obj_list))
3
list(set(obj_list)) == obj_list
True

I expected the final line of code to return False, and the one before it to return 2, since obj_list only contains two unique entries. Why does the set operation not work properly with my custom-defined eq method? How do I need to alter MyObject to get the behavior I am looking for?

Community
  • 1
  • 1
aph
  • 1,765
  • 2
  • 19
  • 34

0 Answers0