1

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?

2
  • Instead of asking a separate question for each method needed to emulate a deque, you should skim the Data model section of the docs (that you've now been given links to in both questions). Almost everything you're likely to ask for is going to be there. Commented Sep 8, 2014 at 3:19
  • Also see collections.abc.MutableSequence. If you inherit from that, and implement the give methods listed in the table, it'll automatically give you all the other methods that deque, list, and similar types have. (If you're in Python 2.x, it's called collections.MutableSequence, no abc… but if you're in 2.x, you shouldn't be declaring a class with no bases like this, as someone else explained on your previous question.) Commented Sep 8, 2014 at 3:21

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you're going to implement __getitem__ and __setitem__, unless you've got an explicitly-fixed-size collection, you probably also want __delitem__ (and probably insert and append and so on, too).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.