首页 > 解决方案 > Python set __contains__ 没有找到集合中包含的对象

问题描述

(Linux上的python 3.7.1)

我观察到一些奇怪的行为,将用户定义的对象存储在一个集合中。这些对象非常复杂,因此不会有一个最小的例子——但我希望观察到的行为能引起比我更聪明的人的解释。这里是:

>>> from mycode import MyObject
>>> a = MyObject(*args1)
>>> b = MyObject(*args2)
>>> a == b
False
>>> z = {a, b}
>>> len(z)
2
>>> a in z
False

我的理解是,如果(1)它的散列与集合中对象的散列匹配并且(2)它等于该对象,则该对象是“在”集合中的。但是这些期望在这里被违反了:

>>> [hash(t) for t in z]
[1013724486348463466, -1852733432963649245]
>>> hash(a)
1013724486348463466
>>> [(hash(t) == hash(a), t == a) for t in z]
[(True, True), (False, False)]
>>> [t is a for t in z]
[True, False]

还有最奇怪的(语法上):

>>> [t in z for t in z]
[False, False]

什么可能MyObject导致它以这种方式运行?回顾一下:它有一个理智__hash____eq__功能,set只是一个股票 python 集。

它们具体在这里:

class MyObject(object):
    ...
        def __hash__(self):
            return hash(self.link)

        def __eq__(self, other):
            """
            two entities are equal if their types, origins, and external references are the same.
            internal refs do not need to be equal; reference entities do not need to be equal
            :return:
            """
            if other is None:
                return False
            try:
                is_eq = (self.external_ref == other.external_ref
                         and self.origin == other.origin
                         and self.entity_type == other.entity_type)
            except AttributeError:
                is_eq = False
            return is_eq

所有这些属性都在这些对象上定义。如上所示,对集合中的一个对象a == t进行评估True。感谢您的任何建议。

标签: pythonsetcontains

解决方案


在将对象添加到集合后,我正在对其进行变异。定义的散列函数不是静态的。


推荐阅读