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