[Numpy-discussion] subclassing float64 (and friends)

eric jones eric at enthought.com
Wed Jan 3 04:29:10 CST 2007


Hey all,

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?

thanks,
eric

class MyFloat(float):

    def __new__(cls, data, my_attr=None):
        obj = float.__new__(cls, data)
        obj.my_attr = my_attr
        return obj

a = MyFloat(1.2,my_attr="hello")
print a, a.my_attr

output:
    1.2 hello


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'


More information about the Numpy-discussion mailing list