Create a python object that can be accessed with square brackets

Python

Python Problem Overview


I would like to create a new class that acts as a special type of container for objects, and can be accessed using square brackets.

For example, suppose I have a class called ListWrapper. Suppose obj is a ListWrapper. When I say obj[0], I expect the method obj.access() to be called with 0 as an argument. Then, I can return whatever I want. Is this possible?

Python Solutions


Solution 1 - Python

You want to define the special __getitem__[docs] method.

class Test(object):     
    def __getitem__(self, arg):
        return str(arg)*3

test = Test()

print test[0]
print test['kitten']

Result:

000
kittenkittenkitten

Solution 2 - Python

Python's standard objects have a series of methods named __something__ which are mostly used to allow you to create objects that hook into an API in the language. For instance __getitem__ and __setitem__ are methods that are called for getting or setting values with [] notation. There is an example of how to create something that looks like a subclass of the Python dictionary here: https://github.com/wavetossed/mcdict

Note that it does not actually subclass dictionary and also, it has an update method. Both of these are necessary if you want your class to properly masquerade as a Python dictionary.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOrdView Question on Stackoverflow
Solution 1 - PythonAcornView Answer on Stackoverflow
Solution 2 - PythonMichael DillonView Answer on Stackoverflow