【发布时间】:2015-07-10 22:13:36
【问题描述】:
为什么python中的切片对象不可哈希:
>>> s = slice(0, 10)
>>> hash(s)
TypeError Traceback (most recent call last)
<ipython-input-10-bdf9773a0874> in <module>()
----> 1 hash(s)
TypeError: unhashable type
它们似乎是不可变的:
>>> s.start = 5
TypeError Traceback (most recent call last)
<ipython-input-11-6710992d7b6d> in <module>()
----> 1 s.start = 5
TypeError: readonly attribute
上下文,我想制作一个字典,将 python 整数或切片对象映射到某些值,如下所示:
class Foo:
def __init__(self):
self.cache = {}
def __getitem__(self, idx):
if idx in self.cache:
return self.cache[idx]
else:
r = random.random()
self.cache[idx] = r
return r
作为一种解决方法,我需要特殊情况切片:
class Foo:
def __init__(self):
self.cache = {}
def __getitem__(self, idx):
if isinstance(idx, slice):
idx = ("slice", idx.start, idx.stop, idx.step)
if idx in self.cache:
return self.cache[idx]
else:
r = random.random()
self.cache[idx] = r
return r
这没什么大不了的,我只是想知道这背后是否有一些原因。
【问题讨论】:
标签: python