Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement list-like index access in Python

I'd like to be able to access some values of a python object using array-like syntax, ie:

obj = MyClass() zeroth = obj[0] first = obj[1] 

Is this possible? If so, how do you implement this in the python class in question?

like image 214
PeterJCLaw Avatar asked Jun 26 '11 20:06

PeterJCLaw


People also ask

Can we access list using index in Python?

You can access the index even without using enumerate() . Using a for loop, iterate through the length of my_list . Loop variable index starts from 0 in this case. In each iteration, get the value of the list at the current index using the statement value = my_list[index] .

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

How are lists indexed in Python?

python lists are 0-indexed. So the first element is 0, second is 1, so on. So if the there are n elements in a list, the last element is n-1.

How do you access a list element in Python?

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.


1 Answers

You need to write or override __getitem__, __setitem__, and __delitem__.

So for example:

class MetaContainer():     def __delitem__(self, key):         self.__delattr__(key)      def __getitem__(self, key):         return self.__getattribute__(key)      def __setitem__(self, key, value):         self.__setattr__(key, value) 

This is a very simple class that allows indexed access to its attributes.

like image 162
senderle Avatar answered Oct 07 '22 21:10

senderle