Mathieu Moalic
Mathieu Moalic

Reputation: 1

Overriding __getitem__

I'm building a class and looking to make the following "numpy like" syntax work:

#simple example
class MyClass():
    def __init__(self):
        self.arr = [1,2,3,4]

    def __getitem__(self, index):
        return self.arr[index]
    
    def print_next(self,index):
        print(self.arr(index+1))

    def print_previous(self,index):
        print(self.arr(index-1))

a = MyClass()
a.arr[2].print_next() #4
a.arr[2].print_previous() #2

__getitem__ only allows me to access the index and not the method call that comes after. I'm looking into metaclasses to change __getitem__ but I can't figure out how to proceed.

Upvotes: 0

Views: 54

Answers (1)

Chrispresso
Chrispresso

Reputation: 4061

You can do something like this:

In [86]: class MyClass():
    ...:     def __init__(self):
    ...:         self.arr = [1,2,3,4]
    ...:         self.index = None
    ...:
    ...:     def __getitem__(self, index):
    ...:         self.index = index
    ...:         return self
    ...:
    ...:     def print_next(self):
    ...:         print(self.arr[self.index+1])
    ...:
    ...:     def print_previous(self):
    ...:         print(self.arr[self.index-1])
    ...:

You don't actually need another argument for print_next or print_previous since you're hoping to call a method again.

Although this isn't recommended since you're overriding __getitem__ to just return self and set a variable.

But now you can do this:

In [90]: a[2].print_next()
4
In [91]: a[2].print_previous()
2

Upvotes: 1

Related Questions