自定义索引Python数据结构

时间:2014-09-08 02:47:05

标签: python

我有一个包含来自deque的python collections的类。当我去创建一个deque x=deque()时,我想引用第一个变量....

In[78]: x[0]
Out[78]: 0

我的问题是如何在以下示例包装器中使用[]进行引用

class deque_wrapper:
    def __init__(self):
        self.data_structure = deque()

    def newCustomAddon(x):
        return len(self.data_structure)

    def __repr__(self):
        return repr(self.data_structure)

,继续上面的例子:

In[75]: x[0]
Out[76]: TypeError: 'deque_wrapper' object does not support indexing

我想自定义我自己的引用,这可能吗?

1 个答案:

答案 0 :(得分:4)

您想要实施__getitem__ method

class DequeWrapper:
    def __init__(self):
        self.data_structure = deque()

    def newCustomAddon(x):
        return len(self.data_structure)

    def __repr__(self):
        return repr(self.data_structure)

    def __getitem__(self, index):
        # etc

每当你执行my_obj[x]时,Python实际上会调用my_obj.__getitem__(x)

如果适用,您可能还需要考虑实施__setitem__ method。 (当您编写my_obj[x] = y时,Python实际上将运行my_obj.__setitem__(x, y)

Python data models上的文档将包含有关在Python中创建自定义数据结构时需要实现哪些方法的更多信息。