4

Python 里 immutable和hashable的概念

 3 years ago
source link: https://www.lfhacks.com/tech/immutable-hashable-in-python
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 里 immutable和hashable的概念

844.jpg

Python 里有两个紧密联系的概念: immutable和hashable. 都是描述一个对象的属性。

immutable

immutable指对象一经创建,即不可修改。对象是不是immutable取决于数据类型,下列类型属于 immutable

  1. 整型(integer)
  2. 浮点型 (float)
  3. 字符串(string)
  4. 元组(tuple)
  5. 布尔值()

下列类型属于 mutable

  1. 列表(list)
  2. 字典(dictionary)
  3. 集合(set)

immutable 不可修改体现在:

1. 字符串不能原位(in-place)修改,而list可以:

>>> string = 'Hello'
>>> string[3:] = 'a'
Traceback (most recent call last):
  File "<>", line 1, in <module>
    string[3:]='a'
TypeError: 'str' object does not support item assignment
>>>
>>> lst=[1,2,3,4]
>>> lst[2:] = [1]
>>> lst
[1, 2, 1]

2. tuple没有方法,而list有很多

>>> t = (1, 2, 3)
>>> t.remove(1)
Traceback (most recent call last):
  File "<>", line 1, in <module>
     t.remove(1)
AttributeError: 'tuple' object has no attribute 'remove'
>>> t.append(1)
Traceback (most recent call last):
  File "<>", line 1, in <module>
  t.append(1)
AttributeError: 'tuple' object has no attribute 'append'
>>> 
>>> l = [1, 2, 3]
>>> l.remove(3)
>>> l
[1, 2]
>>> l.append(3)
>>> l
[1, 2, 3]

于是,immutable的对象可以作为一个固定不变的对象,适合作为哈希表的索引,因而它们是hashable的。

hashable

哈希表是在一个关键字和一个较大的数据之间建立映射的表,能使对一个数据序列的访问过程更加迅速有效。用作查询的关键字必须唯一且固定不变,于是只有immutable的对象才可以作为键值,“可以作为键值”这种属性,叫hashable.
如上所述,整型(integer)、字符串(string)和元组(tuple)都可以作为键值,而list不可以。

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

immutable与unchangable

tuple是immutable的,即使它包含一个mutable的元素后成为changable,仍然可以认为tuple是immutable的,因为他作为一个容器,里面包含对象并没有变化。

>>> t = ([1, 2, 3], 4, 5)
>>> t[0][0] = 0
>>> t
([0, 2, 3], 4, 5)
>>> t[0] = 0
Traceback (most recent call last):
  File "<>", line 1, in <module>
    t[0] = 0
TypeError: 'tuple' object does not support item assignment

所以,immutable和unchangable是不排斥、不相关的两个属性。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK