Hashable v.s. Immutable

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__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().

>>> a = 1
>>> a.__hash__()
1
>>> hash(a)
1

>>> a = 1.2
>>> hash(a)
461168601842738689

>>> import collections
>>> isinstance([2,3], collections.Hashable)
False
>>> isinstance(2, collections.Hashable)
True

>>> a = {[2,3]:1}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

immutable

An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.

mutable

Mutable objects can change their value but keep their id().

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same value.(因为内存re-use)

CPython implementation detail: This is the address of the object in memory.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • The Python Data Model If you learned another object-orien...
    plutoese阅读 5,753评论 0 51
  • 好久没有去唱歌了,是工作太忙吗?可也没看到工作的成绩在哪,似乎也是随波逐流!忽然间听了《黄昏》,让我情不自禁的融入...
    lhl2阅读 1,040评论 1 0
  • 鹿晗被我画成了Q版,这是个绘图的问题。
    朕想统一天下阅读 3,110评论 14 7
  • 女孩兴奋地奔向那破烂的出租屋。 这是她的家。 “妈妈!你看,这本书的封面好看吗?这可是我……” 中年妇人没有看到女...
    虞美人s阅读 1,794评论 0 2