分享

python中可hash的对象

 shhu1993 2014-12-18

看核心编程时候有个叫hash的东西,呵呵,打开python文档看看:

hashable(可哈希性)

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

(如果一个对象是可哈希的,那么在它的生存期内必须不可变(需要一个哈希函数),而且可以和其他对象比较(需要比较方法).比较值相同的对象一定有相同的哈希值)

翻译的比较生硬...简单的说就是生存期内可变的对象不可以哈希,就是说改变时候其id()是不变的.基本就是说列表,字典,集合了.


写一段代码验证一下:

a= [0,0,0]
b = {1:2,'c':9}
c = set(a)
string = 'hello'

class A():
    pass
a = A()
print hash(A)
print hash(a)
print hash(string)

print hash(c)
print hash(b)
print hash(a)

可以看出列表,字典,集合是无法哈希的,因为他们在改变值的同时却没有改变id,无法由地址定位值的唯一性,因而无法哈希.



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多