I want to create a class that holds a 2D numpy array with arbitrary n x m size. The class could look like
Class Img:
def __init__(self, data):
self.data = data
Say that I have read such a 2D array called sample
hence,
A = Img(sample)
I would like to be able to access the values in A in the following way,
value = A[2, 3] # this would return the value at row= 2 and column=3
Rather than this,
value = A.data[2,3]
Is there a way to achieve this?
Hope this makes sense.
Thanks
Have a look a the __getitem__
special method.
See 3. Data model — Python 3.12.1 documentation
Maybe that is what you want?
Note that the key will need to be a tuple.
So that the access is:
value = A[(2,3)]
MRAB
(Matthew Barnett)
December 15, 2023, 8:09pm
3
The key doesn’t need to be a tuple. A[(2, 3)]
and A[2, 3]
are treated the same.
Also, the __init__
method in the original post was missing self
.
Thank you @barry-scott and @MRAB I will check this out!!
Thanks @MRAB I just corrected this!
For those who might be interested. Here is the solution.
Class Img:
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
So if I have a 2D array called sample
hence,
A = Img(sample)
I can access the values in A in the following way,
value = A[2, 3] # this would return the value at row= 2 and column=3
Note that there is no check here as to whether the key values are within the proper bounds.
Thanks again to @barry-scott and @MRAB