Picani Picani - 1 year ago 82
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


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download