[SciPy-user] Subclassing array
Michael McNeil Forbes
mforbes at phys.washington.edu
Tue Oct 24 19:43:36 CDT 2006
I have a question about the best way to subclass array types.
I would like to create a subclass of the array types that allows me to
name the entries of the array. Here is a sample of my desired usage:
>>> from scipy import *
>>> a = array([1.0,2.0])
>>> class MyArray(a.__class__):
>>> _names = ['x','y']
>>> ... (redefine __get__ etc. as needed)
>>> c = MyArray(x=2,y=3)
>>> c.x, c.y
I want c to be an array with two elements, but essentially want to be
able to change c.__class__ to be a modified class that can access
elements as specified by c._names.
Ideally, I would like this to work with any type that supports simple
indexing, such as arrays, lists etc. but my first attempts seem to
require redefining __new__ which varies for different types making the
solution much less general.
It seems like I should be able to get the desired behaviour with
something like the following:
self = deepcopy(a)
self[:] = map(kwargs.get,cls._names)
self.__class__ = cls
but this is not allowed because __class__ can only be set for heap types.
Is there a standard and safe way to achieve this behaviour?
More information about the SciPy-user