python--用户自定义类对象作为dict的key

PS: 学好了Java,学Python 会容易

在Java 中如果 用户自定义的类要作为HashMap的key, 则这个类需要实现equals 和 hashCode ,在python 中也是相同的只不过相应的函数名称发生了变化,变为__hash__ 和__eq__ 

参考

http://docs.python.org/2/library/functions.html?highlight=hash#hash

http://docs.python.org/2/reference/datamodel.html#object.__hash__

__hash__ 函数必须返回整数值, 另外需要留意的函数是hash() , 这个函数是内建函数,可以返回一个对象的hash值,如果有的话(其实就是如果实现了__hash__) ,否则返回的对象在内存中的地址

下面看一段代码的例子

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

    def __hash__(self):
        return hash(self.name + str(self.age))

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

dd = {}
a = MemDev('zhangsan',4)
print hash(a)
b = MemDev('zhangsan',4)
print hash(b)
dd[a] =5
dd[b] = 6
dd[MemDev('lisi',6)] = 7
for item in dd:
    print item, dd[item]

执行结果:

-811027391
-811027391
<__main__.MemDev object at 0xb76c0bcc> 6
<__main__.MemDev object at 0xb76c0d8c> 7


set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built in dictlist, and tuple classes, and the collections module.)


所以情况同样适用于set



你可能感兴趣的:(python)