2

I have a class that handles a Numpy matrix and some additional infos.

import numpy as np

class MyClass:
    def __init__(self, v):
        self.values = v

plop = MyClass(np.matrix([[1, 2], [3, 4]]))

The matrix being named values, to access it, I write:

plop.values[1, 1]  # Returns 4

Is it possible to access it directly? I mean, doing:

plop[1, 1]  # Should returns 4 too

I saw this post but it seams that this solution allows only one level of [].

Thanks!

2
  • plop = np.matrix([[1, 2], [3, 4]]); plop[1, 1] ? Commented Nov 22, 2016 at 14:00
  • 2
    Actually, there are others attributes to MyClass that I didn't write here. Commented Nov 22, 2016 at 14:12

2 Answers 2

4

Just add this method to you class

def __getitem__(self, indices):
    return self.values[indices]

Also, given the opportunity, it would be useful to see how __getitem__ and slice objects work

Sign up to request clarification or add additional context in comments.

Comments

-1

you access it directly I think.

plop = np.matrix([[1, 2], [3, 4]])

plot[1, 1]

1 Comment

To quote OP: "there are others attributes to MyClass that I didn't write here" so plop must be an instance of MyClass

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.