Skip to content
Advertisement

Python: get attribute from class objects stored in an array

I would like to get the attribute of every object contained in an ndarray. Consider the following code, where after vectorization the function returns an ndarray with the objects. From each of these objects in the array, I would like to get the attribute and store the attributes in a new array.

The classes and functions are a dummy for more complex classes and functions. I am aware of the fact that from stud = new_student(["Michael","Rachel"], [1,2]); stud.name I could get a list with the names, however this is not possible with the function I am using instead of new_student.

JavaScript

Advertisement

Answer

JavaScript

With the added repr the array now prints:

JavaScript

When you try name, you get:

JavaScript

You really should have shown this error. Do you understand what’s going on? Just because objects in the array have that attribute, doesn’t mean that the array itself has it.

Consider a list of the same objects. Asking for the name of the list doesn’t make any sense either.

JavaScript

You still have to ask each element for that attribute:

JavaScript

You could use np.vectorize, as you did with the constructor, to fetch the attributes (or np.frompyfunc), but the results, and timings, are basically the same. Using an object array instead of a list has few, if any, advantages.

The idealize “vectorization” only applies to numeric dtypes. The fast compiled code is written in c using the c numeric types like floats and doubles. Object dtypes require referencing Python objects in the same way as lists.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement