[SciPy-user] Subclassing array
Michael McNeil Forbes
mforbes at phys.washington.edu
Tue Oct 24 20:43:36 EDT 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
(2, 3)
etc.
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:
def __new__(cls,**kwargs):
self = deepcopy(a)
self[:] = map(kwargs.get,cls._names)
self.__class__ = cls
return 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?
Thanks,
Michael.
More information about the SciPy-User
mailing list