immutable immutable指对象一经创建,即不可修改。对象是不是immutable取决于数据类型,下列类型属于 immutable 整型(integer) 浮点型 (float) 字符串(string) 元组(tuple) 布尔值() 下列类型属于 mutable 列表(list) 字典(dictionary) 集合(set) immutable 不可修改体现在: 字符串不能原位(in-place)修改,而 list 可以: # Python REPL >>> string = 'Hello' >>> string[3:] = 'a' Traceback (most recent call last): File "<>", line 1, in string[3:]='a' TypeError: 'str' object does not support item assignment >>> >>> lst=[1,2,3,4] >>> lst[2:] = [1] >>> lst [1, 2, 1] tuple没有方法,而list有很多 # Python REPL >>> t = (1, 2, 3) >>> t.remove(1) Traceback (most recent call last): File "<>", line 1, in t.remove(1) AttributeError: 'tuple' object has no attribute 'remove' >>> t.append(1) Traceback (most recent call last): File "<>", line 1, in 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不可以。 # Python REPL >>> 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 d = {1:2, 'Ben':123, [1,2,3]:456} TypeError: unhashable type: 'list' immutable与unchangable tuple是immutable的,即使它包含一个mutable的元素后成为changable,仍然可以认为tuple是immutable的,因为他作为一个容器,里面包含对象并没有变化。 # Python REPL >>> 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 t[0] = 0 TypeError: 'tuple' object does not support item assignment 所以,immutable和unchangable是不排斥、不相关的两个属性。