Introducing fancy class indexing

Some libraries, such as numpy, pandas, or even python lists, implement fantastic indexing for their objects. This means that I can do things like:

obj[1:3, :] 

If I want to offer this function in my class, I can try to overload the __getitem__ and __setitem__ methods:

 class Example(object): def __getitem__(self, x): pass 

but I don’t see how this can work, since 1:3 not a valid variable name. How can this functionality be achieved?

+6
source share
2 answers

The only thing about slice notation is the abbreviation for slice , which makes your code equivalent:

 obj[(slice(1, 3), slice(None, None))] 

The parameter passed to __getitem__ is the "index" of the element, which can be any object:

 def __getitem__(self, index): if isinstance(index, tuple): # foo[1:2, 3:4] elif isinstance(index, slice) # foo[1:2] else: # foo[1] 
+5
source

Slices of type 1:3 converted into slice objects and passed to your function. If you have multiple pointers, they turn into tuple . To demonstrate:

 >>> class Example(object): ... def __getitem__(self, index): ... return index ... >>> example = Example() >>> example['hello'] 'hello' >>> example[1:5] slice(1, 5, None) >>> example[1:5, 10:15] (slice(1, 5, None), slice(10, 15, None)) 
+6
source

Source: https://habr.com/ru/post/953449/


All Articles