我听说过“不变的物体是可持续的”这句话,下面是这样,
弗罗森塞特是不变的,永远是可持续的。
但是tuples是不可变的,但不是可持续的?为什么?
发布于 2014-03-12 06:14:33
如果里面的元素是可理解的,那么元组是非常可理解的。
>>> 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'
>>> 发布于 2014-03-12 05:49:45
并非所有不变的对象都是可理解的。此外,只有包含可变对象的元组才是不可接受的。
>>> 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'所以,问题在于列表,而不是元组。
发布于 2014-03-12 05:52:34
即使元组本身是不可变的,它们也可能包含可变对象,例如,如果我们可以这样做的话:
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?https://stackoverflow.com/questions/22342931
复制相似问题