在python中 - 如果对象在集合中,则集合用于测试的运算符

nin*_*o64 10 python overriding object set

如果我有一个对象列表,我可以使用该__cmp__方法来覆盖对象进行比较.这会影响==操作员的工作方式和item in list功能.但是,它似乎没有影响item in set函数 - 我想知道如何更改MyClass对象,以便我可以覆盖集合比较项目的行为.

例如,我想创建一个在底部的三个print语句中返回True的对象.目前,最后一个print语句返回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
Run Code Online (Sandbox Code Playgroud)

Ada*_*ner 9

set采用__hash__了比较.覆盖它,你会很好:

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
Run Code Online (Sandbox Code Playgroud)