Picani Picani - 16 days ago 6
Python Question

Python: Directly access to attribute in a dict-like way

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!

Answer

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