user1234440
user1234440

Reputation: 23577

Custom Indexing Python Data Structure

I have a class that wraps around python deque from collections. When I go and create a deque x=deque(), and I want to reference the first variable....

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

My question is how can use the [] for referencing in the following example wrapper

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)

Ie, continuing from above example:

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

I want to customize my own referencing, is that possible?

Upvotes: 1

Views: 513

Answers (1)

Michael0x2a
Michael0x2a

Reputation: 64188

You want to implement the __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

Whenever you do my_obj[x], Python will actually call my_obj.__getitem__(x).

You may also want to consider implementing the __setitem__ method, if applicable. (When you write my_obj[x] = y, Python will actually run my_obj.__setitem__(x, y).

The documentation on Python data models will contain more information on which methods you need to implement in order to make custom data structures in Python.

Upvotes: 4

Related Questions