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

女生的网名这么多〃 提交于 2019-12-10 12:39:32

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/8675105/in-python-the-operator-which-a-set-uses-for-test-if-an-object-is-in-the-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!