最近我发现了一个有趣的发现,有些东西会影响类的对象/实例的哈希性。我想知道怎么做,为什么?你知道吗
例如,我得到了一个名为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__
的情况下再次可散列。你知道吗
因此,引入了uu eq uuu()方法,将uu hash uuu()设置为None。您可以添加自定义哈希,以允许进行上述构造:
更多信息可以在这里找到:https://docs.python.org/3/reference/datamodel.html#object.hash
相关问题 更多 >
编程相关推荐