I am attempting to use a class that strings together several instances of another class as a numpy array of objects. I want to be able to concatenate attributes of the instances that are contained in the numpy array. I figured out a sloppy way to do it with a bunch of for loops, but I think there must be a more elegant, pythonic way of doing this. The following code does what I want, but I want to know if there is a cleaner way to do it:
import numpy as np
class MyClass(object):
def __init__(self):
self.a = 37.
self.arr = np.arange(5)
class MyClasses(object):
def __init__(self):
self.N = 5
# number of MyClass instances to become attributes of this
# class
def make_subclas_arrays(self):
self.my_class_inst = np.empty(shape=self.N, dtype="object")
for i in range(self.N):
self.my_class_inst[i] = MyClass()
def concatenate_attributes(self):
self.a = np.zeros(self.N)
self.arr = np.zeros(self.N * self.my_class_inst[0].arr.size)
for i in range(self.N):
self.a[i] = self.my_class_inst[i].a
slice_start = i * self.my_class_inst[i].arr.size
slice_end = (i + 1.) * self.my_class_inst[i].arr.size
self.arr[slice_start:slice_end] = (
self.my_class_inst[i].arr )
my_inst = MyClasses()
my_inst.make_subclas_arrays()
my_inst.concatenate_attributes()
Edit: Based on the response from HYRY, here is what the methods look like now:
def make_subclass_arrays(self):
self.my_class_inst = np.array([MyClass() for i in range(self.N)])
def concatenate_attributes(self):
self.a = np.hstack([i.a for i in self.my_class_inst])
self.arr = np.hstack([i.arr for i in self.my_class_inst])