Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a python object that can be accessed with square brackets

Tags:

python

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?

like image 910
Ord Avatar asked Oct 30 '11 00:10

Ord


People also ask

How do you use square brackets in Python?

The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from postion 0 to position 13.

What does 2 square brackets mean in Python?

Indexing DataFrames You can either use a single bracket or a double bracket. The single bracket will output a Pandas Series, while a double bracket will output a Pandas DataFrame.

Are square brackets a list in Python?

What is a Python list? A list is an ordered and mutable Python container, being one of the most common data structures in Python. To create a list, the elements are placed inside square brackets ([]), separated by commas.

What brackets to use in Python?

[] (Index brackets) Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.


2 Answers

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
like image 86
Acorn Avatar answered Oct 29 '22 12:10

Acorn


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.

like image 40
Michael Dillon Avatar answered Oct 29 '22 13:10

Michael Dillon