如何判断一个对象/实例是否为哈希值

2024-04-25 21:50:12 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我发现了一个有趣的发现,有些东西会影响类的对象/实例的哈希性。我想知道怎么做,为什么?你知道吗

例如,我得到了一个名为ListNode的链表类:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

   def __repr__(self):
        if self.next:
            return "{}->{}".format(self.val, repr(self.next))
        else:
            return "{}".format(self.val)

    # def __eq__(self, other):
        # if not self and not other:
        #     return True
        # elif not self or not other:
        #     return False
        # else:
        #     return self.val == other.val and self.next == other.next

     # def __eq__(self, other):
        # return str(self) == str(other)

注意,我阻止了__eq__方法。 现在,如果我创建一个实例:

A = ListNode(1)
B = ListNode(2)
C = ListNode(3)
A.next = B
B.next = C
print(hash(A))

然后它是可散列的,但是,每次运行它时,我都会得到不同的输出编号。你知道吗

现在如果我取消阻止__eq__方法,它突然就不再是可散列的了。为什么?你知道吗

似乎hash方法将使用__eq__。在启用__eq__之后,它如何知道它是不可散列的?你知道吗

附加: 如果我编写__eq__方法来比较两个链表的str版本(第二个__eq__方法),我认为这可以解决这个问题,因为通过将链表转换成string,它就变成了一个可散列数据,但我仍然得到unhashable错误消息

谢谢!你知道吗

According to @juanpa.arrivillaga's comment:

__eq__将删除默认的__hash__方法,使其不可损坏。 所以我添加了我自己的__hash__方法:

def __hash__(self):
    return hash(id(self))

这解决了问题,并使ListNode在启用__eq__的情况下再次可散列。你知道吗


Tags: 实例方法selfreturndefnotvalhash
1条回答
网友
1楼 · 发布于 2024-04-25 21:50:12

If a class does not define an __eq__() method it should not define a __hash__() operation either; if it defines __eq__() but not __hash__(), its instances will not be usable as items in hashable collections.

(...)

A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None. When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking isinstance(obj, collections.abc.Hashable). 1

因此,引入了uu eq uuu()方法,将uu hash uuu()设置为None。您可以添加自定义哈希,以允许进行上述构造:

def __hash__(self):
    return self.val

更多信息可以在这里找到:https://docs.python.org/3/reference/datamodel.html#object.hash

相关问题 更多 >