如何將對象正確地轉換為可哈希的?

2024-05-18 17:42:21 发布

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

这是我的代码:

class Hero:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name + str(self.age)

    def __hash__(self):
        print(hash(str(self)))
        return hash(str(self))

heroes = set()

heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 1

heroes.add(Hero('Lara Miheenko', 17)) # gets hash -2822451113328084695
print(len(heroes)) # gets 2

heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 3! WHY?

为什么会这样?
第一个和第三个对象有相同的内容和相同的散列,但是len()告诉了3个唯一的对象?


Tags: nameselfaddagelenreturndefhash
3条回答

下面是整个代码:

class Hero:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name + str(self.age)

    def __hash__(self):
        print(hash(str(self)))
        return hash(str(self))

    def __eq__(self,other):
        return self.name == other.name and self.age== other.age



heroes = set()
heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 1

heroes.add(Hero('Lara Miheenko', 17)) # gets hash -2822451113328084695
print(len(heroes)) # gets 2

heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 2 

函数识别__eq__,因此len是2。

The Python documentation可能有帮助:

If a class does not define a __cmp__() or __eq__() method it should not define a __hash__() operation either;

您还需要以与^{}兼容的方式定义__eq__(),否则,等式将基于对象标识。

在Python 2上,建议还定义__ne__,使!===一致。在Python 3上,默认的__ne__实现将为您委托给__eq__

相关问题 更多 >

    热门问题