有没有办法以支持整数和切片索引的方式实现 __getitem__
而无需手动检查参数类型?
我看到了很多这种形式的例子,但我觉得它很老套。
def __getitem__(self,key):
if isinstance(key,int):
# do integery foo here
if isinstance(key,slice):
# do slicey bar here
相关说明,为什么这个问题首先存在?有时返回一个 int 有时返回一个 slice 是奇怪的设计。调用 foo[4]
应该调用 foo.__getitem__(slice(4,5,1))
或类似的。
最佳答案
您可以使用异常处理;假设 key
是一个 slice
对象并对其调用 indices()
方法。如果失败,它一定是一个整数:
def __getitem__(self, key):
try:
return [self.somelist[i] * 5 for i in key.indices(self.length)]
except AttributeError:
# not a slice object (no `indices` attribute)
return self.somelist[key] * 5
大多数自定义容器的用例不需要支持切片,而且从历史上看,__getitem__
方法只需要处理整数(对于序列,即); __getslice__()
method是用来处理切片的吗?当 __getslice__
被弃用时,为了向后兼容 和 对于更简单的 API,让 __getitem__
处理整数和 slice
对象。
这忽略了外部序列的事实,key
不必是整数。自定义类可以自由支持他们喜欢的任何键类型。
关于python - 实现 __getitem__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22151335/