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



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值