不可变对象在python中不可删除?

时间:2014-03-12 05:43:19

标签: python hashmap immutability

我听说过这行"不可变对象是可以使用的#34;,就像这样,

  

Frozensets是不可变的,总是可以随意使用。

但是tuples不可变的但不可以播放?为什么呢?

3 个答案:

答案 0 :(得分:3)

如果里面的元素是可以清洗的,那么元组非常易于使用。

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

答案 1 :(得分:1)

并非所有不可变对象都是可清除的。此外,只有包含可变对象的元组不可清除。

>>> t = (1, 2)
>>> hash(t)
1299869600
>>> t = ([1], [2])  
>>> hash(t)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    hash(t)
TypeError: unhashable type: 'list'

所以,问题是列表,而不是元组。

答案 2 :(得分:1)

即使元组本身是不可变的,它们也可能包含可变对象,例如,如果可以的话:

person = {'name': 'John', 'surname': 'Doe'}
key = (person, True)

cache = {}
cache[key] = datetime.now()  # for example

person['surname'] = 'Smith'

cache[key]  # What is the expected result?
相关问题