自定义索引Python数据结构

2024-04-23 15:56:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类围绕着来自collections的pythondeque。当我去创建一个dequex=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

我想自定义我自己的引用,可以吗?你知道吗


Tags: inself示例datareturndefoutwrapper
1条回答
网友
1楼 · 发布于 2024-04-23 15:56:27

要实现^{} 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)。你知道吗

如果适用,您还可以考虑实现^{} method。(当您编写my_obj[x] = y时,Python实际上将运行my_obj.__setitem__(x, y)。你知道吗

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

相关问题 更多 >