问题:自定义类型的对象作为字典键
如何将自定义类型的对象用作Python字典中的键(我不希望“对象id”用作键),例如
class MyThing:
    def __init__(self,name,location,length):
            self.name = name
            self.location = location
            self.length = length如果名称和位置相同,我想将MyThing用作相同的键。从C#/ Java开始,我习惯于重写并提供一个equals和hashcode方法,并保证不会突变该hashcode依赖的任何内容。
我必须在Python中做什么才能做到这一点?我应该吗?
(在一个简单的例子中,就像这里一样,也许最好将一个(名称,位置)元组放置为键-但考虑到我希望键成为一个对象)
回答 0
您需要添加2种方法,注意__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)回答 1
使用python 2.6或更高版本的替代collections.namedtuple()方法-它可以节省编写任何特殊方法的时间:
from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj
a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False回答 2
__hash__如果需要特殊的哈希语义,则可以覆盖,__cmp__或者__eq__为了使您的类可用作键。比较相等的对象需要具有相同的哈希值。
Python期望__hash__返回一个整数,Banana()不建议返回:)
如您所述,用户定义的类在__hash__默认情况下会调用id(self)。
文档中还有一些其他技巧:
__hash__()从父类继承方法但更改的含义__cmp__()或__eq__()使得返回的哈希值不再合适的类(例如,通过切换到基于值的相等性概念,而不是基于默认的基于身份的相等性),这些类可以显式地标记为可以通过__hash__ = None在类定义中进行设置来取消哈希。这样做意味着,在程序尝试检索其哈希值时,该类的实例不仅会引发适当的TypeError,而且在检查时它们也将被正确标识为不可哈希isinstance(obj, collections.Hashable)(与定义自己__hash__()明确地引发TypeError的类不同 )。

