python - 实现 __getitem__

标签 python

有没有办法以支持整数和切片索引的方式实现 __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/

相关文章:

python - 在表格报告实验室中包装文本?

Python Flask 获取 404 未找到错误

python - 使用 python 在 mysqltable 中进行字符串搜索

python pandas pivot_table 在一列中计算频率

python - 如何更改 Django 错误报告电子邮件的主题?

python - Tensorflow Keras 保留每批的损失

python - 类 lambda 回调 NameError

python - 在平局的情况下字典中的随机最大键

Python 作为可执行程序

python - 通过公式在 python 中定义一个 ndarray