我必须怎么做才能将自定义类型的对象用作 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/