【问题标题】:In python - the operator which a set uses for test if an object is in the set在python中 - 集合用于测试对象是否在集合中的运算符
【发布时间】:2011-12-30 00:53:02
【问题描述】:

如果我有一个对象列表,我可以使用__cmp__ 方法覆盖对象进行比较。这会影响== 运算符的工作方式以及item in list 函数。但是,它似乎不会影响 item in set 函数 - 我想知道如何更改 MyClass 对象,以便我可以覆盖集合比较项目的行为。

例如,我想在底部的三个打印语句中创建一个返回 True 的对象。目前,最后一条打印语句返回 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

【问题讨论】:

    标签: python object set overriding


    【解决方案1】:

    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
    

    【讨论】:

    • 这是因为set 实现使用字典进行存储(其中所有值都被忽略)并且字典包含操作(key in dict_)使用key 的哈希。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2023-02-24
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 2013-06-11
    相关资源
    最近更新 更多