On Wed, Jan 03, 2007 at 04:29:10AM -0600, eric jones wrote: > I am playing around with sub-classing the new-fangled float64 objects > and friends. I really like the new ndarray subclassing features > (__array_finalize__, etc.), and was exploring whether or not the scalars > worked the same way. I've stubbed my toe right out of the blocks > though. I can sub-class from standard python floats just fine, but when > I try to do the same from float64, I get a traceback. (examples below) > Anyone have ideas on how to do this correctly? > > from numpy import float64 > > class MyFloat2(float64): > > def __new__(cls, data, my_attr=None): > obj = float64.__new__(cls, data) > obj.my_attr = my_attr > return obj > > a = MyFloat2(1.2,my_attr="hello") > print a, a.my_attr > > > output: > Traceback (most recent call last): > File "C:\wrk\eric\trunk\src\lib\geo\examples\scalar_subtype.py", > line 33, in ? > a = MyFloat2(1.2,my_attr="hello") > File "C:\wrk\eric\trunk\src\lib\geo\examples\scalar_subtype.py", > line 30, in __new__ > obj.my_attr = my_attr > AttributeError: 'numpy.float64' object has no attribute 'my_attr'
With classes defined in C I've often noticed that you can't add attributes, i.e. f = N.float64(1.2) f.x = 1 breaks with AttributeError: 'numpy.float64' object has no attribute 'x' The way to fix this for arrays is to first view the array as the new subclass, i.e. x = N.array([1]) class Ary(N.ndarray): pass x = x.view(Ary) x.y = 1 However, with floats I noticed that the following fails: import numpy as N f = N.float64(1.2) class Floaty(N.float64): pass f.view(Floaty) with TypeError: data type cannot be determined from type object Maybe this is part of the problem? Regards Stéfan _______________________________________________ Numpy-discussion mailing list Numpy-discussion@scipy.org http://projects.scipy.org/mailman/listinfo/numpy-discussion