python - 自定义类型的对象作为字典键

我必须怎么做才能将自定义类型的对象用作 Python 字典中的键(我不希望“对象 id”充当键),例如

class MyThing:
    def __init__(self,name,location,length):
            self.name = name
            self.location = location
            self.length = length

如果名称和位置相同,我想将 MyThing 用作被视为相同的键。 从 C#/Java 开始,我习惯于重写并提供 equals 和 hashcode 方法,并 promise 不会改变 hashcode 所依赖的任何内容。

我必须在 Python 中做什么才能完成此任务?我什至应该吗?

(在一个简单的情况下,比如这里,最好只放置一个 (name,location) 元组作为键 - 但考虑我希望键是一个对象)

最佳答案

您需要添加2 methods , 注意 __hash____eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

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

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

python dict documentation定义关键对象的这些要求,即它们必须是 hashable .

https://stackoverflow.com/questions/4901815/

相关文章:

linux - 如何强制从另一个 SSH session 中分离 screen ?

python - Python SciPy 需要 BLAS 吗?

linux - 使用 Bash 自动将最后一个命令的输出捕获到变量中?

c - 编写程序以处理导致 Linux 上丢失写入的 I/O 错误

django - 在 Django 中处理一页上的多个表单的正确方法

linux - 如何检测网线/连接器的物理连接状态?

python - ValueError : The truth value of an array

python - 编码/解码有什么区别?

Python Infinity - 有什么注意事项吗?

linux - 使用 tar、gz、zip 或 bzip2 拆分文件