Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python - the operator which a set uses for test if an object is in the set

If I have a list of objects, I can use the __cmp__ method to override objects are compared. This affects how the == operator works, and the item in list function. However, it doesn't seem to affect the item in set function - I'm wondering how I can change the MyClass object so that I can override the behaviour how the set compares items.

For example, I would like to create an object that returns True in the three print statements at the bottom. At the moment, the last print statement returns False.

class MyClass(object):
    def __init__(self, s):
        self.s = s
    def __cmp__(self, other):
        return cmp(self.s, other.s)

instance1, instance2 = MyClass("a"), MyClass("a")

print instance2==instance1             # True
print instance2 in [instance1]         # True
print instance2 in set([instance1])    # False
like image 835
ninhenzo64 Avatar asked Dec 30 '11 00:12

ninhenzo64


People also ask

How do you check if an object is in a set Python?

To check if the Set contains an element in Python, use the in keyword, which returns True if the specified Set contains an element and False otherwise. The in keyword checks if the item is present in a sequence like a list, range, string, set, etc.

What is the use of set () in Python?

Python set() Function The set() function creates a set object. The items in a set list are unordered, so it will appear in random order. Read more about sets in the chapter Python Sets.

What does == mean in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .


1 Answers

set uses __hash__ for comparison. Override that, and you'll be good:

class MyClass(object):
    def __init__(self, s):
        self.s = s
    def __cmp__(self, other):
        return cmp(self.s, other.s)
    def __hash__(self):
        return hash(self.s) # Use default hash for 'self.s'

instance1, instance2 = MyClass("a"), MyClass("a")
instance3 = MyClass("b")

print instance2==instance1             # True
print instance2 in [instance1]         # True
print instance2 in set([instance1])    # True
like image 89
Adam Wagner Avatar answered Sep 20 '22 16:09

Adam Wagner