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?
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] .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With