在类中实现花哨的索引

时间:2013-09-09 00:01:15

标签: python

像numpy,pandas甚至python列表这样的库为其对象实现了精美的索引。这意味着我可以做以下事情:

obj[1:3, :]

如果我想在课堂上提供此功能,我可以尝试重载__getitem____setitem__方法:

class Example(object):
   def __getitem__(self, x):
      pass

但我不知道这是如何工作的,因为1:3不是有效的变量名。如何实现这一功能?

2 个答案:

答案 0 :(得分:6)

1:3这样的切片会变成slice个对象并传递给您的函数。如果您有多个索引器,则会将它们变为tuple。为了证明:

>>> class Example(object):
...     def __getitem__(self, index):
...         return index
... 
>>> example = Example()
>>> example['hello']
'hello'
>>> example[1:5]
slice(1, 5, None)
>>> example[1:5, 10:15]
(slice(1, 5, None), slice(10, 15, None))

答案 1 :(得分:5)

切片表示法唯一特别之处是slice的简写,它使您的代码等效于:

obj[(slice(1, 3), slice(None, None))]

传递给__getitem__的参数是项目的“索引”,可以是任何对象:

def __getitem__(self, index):
    if isinstance(index, tuple):
        # foo[1:2, 3:4]
    elif isinstance(index, slice)
        # foo[1:2]
    else:
        # foo[1]