Reputation: 187
I think my code will explain what I'm trying to do:
class Book():
def __init__(self, Author, Pages):
self.Author = Author
self.Pages = Pages
def getAuthor(self):
return self.Author
book_1 = Book("Jane Smith", 20)
book_2 = Book("Billy", 20)
B = np.array([book_1, book_2])
print(B[0][1].getAuthor())
Basically, I want to this to print "Billy", the error I am getting is:
TypeError: 'Book' object is not subscriptable
What is the best way to go about doing this?
Upvotes: 1
Views: 1673
Reputation: 114230
Numpy (unlike MATLAB) does not add dimensions to an array that you don't tell it to. So, B = np.array([book_1, book_2])
creates an array of shape (2,)
, not (2, 1)
or (1, 2)
. You can verify this by printing B.shape
.
To access the second element, you just do B[1]
.
When you do B[0][1]
, you are accessing the first element, and then indexing it with [1]
, as if you did book_1[1]
. The error is telling you that that is illegal because you did not implement __getitem__
in your class.
Notes:
You generally don't want to use numpy for object arrays. They offer no advantages over list
, and some disadvantages when it comes to appending elements.
Indexing a multidimensional numpy array is done via a single index (unlike a list, which only supports one dimension at a time). So if B
really was 2D, you would do B[0, 1]
. While you could do B[0][1]
, it actually does something a bit different than B[0, 1]
. B[0]
is a view of the first row of the array. B[0][1]
is an element of that view. This will generally be in the same buffer as the original, but depending on the memory layout and the type of indexing you use, the two approaches may have surprisingly different results.
Upvotes: 3