On Python 2.5 I need to use float numbers with a modified __str__() method. Also I need to know when the constructor fails.
Why I can’t catch exceptions raised from float.__init__()?
What is the best way to consult the numeric value of my derived float object? In my code I’m using float(self).
class My_Number(float):
def __init__(self, float_string):
try:
super(My_Number, self).__init__(float_string)
except (TypeError, ValueError):
raise My_Error(float_string)
def __str__(self):
if int(float(self)) == float(self):
return str(int(float(self)))
else:
return str(round(float(self), 2))
>>> n = My_Number('0.54353')
>>> print n
0.54
>>> n = My_Number('5.0')
>>> print n
5
>>> n = My_Number('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): foo
floatis immutable, therefore its__init__, the initializer, is basically a no-op — nothing substantial can happen there, because theselfobject cannot be altered (if it’s actually an instance offloatrather than of a subclass — but of coursefloat‘s own__init__must operate on that assumption;-).Therefore, all the action happens in
__new__, the constructor proper, just like for other immutable types likeint,str,tuple, and so on. It’s a common mistake to believe that__init__is a constructor: it’s not, it takes an already-constructed object as its first argument,self, and “initializes” it (if feasible, i.e., if thatselfis mutable!-) — the construction itself happens in__new__.So, your
floatsubclass should start:and you can remove the
__init__, which is not needed. Now:(of course, it would work even better if you did have a
My_Errorexception class defined;-).