subclassing Decimal

Steven Bethard steven.bethard at gmail.com
Mon Feb 21 17:07:59 EST 2005


jbauer at rubic.com wrote:
> I was interested in playing around with Decimal and
> subclassing it.  For example, if I wanted a special
> class to permit floats to be automatically converted
> to strings.
> 
>     from decimal import Decimal
> 
>     class MyDecimal(Decimal):
>         def __init__(self, value):
>             if isinstance(value, float):
>                 ... initialize using str(float) ...
> 
> In the classic days, I would have added something
> like this to MyDecimal __init__:
> 
>     Decimal.__init__(self, str(value))
> 
> But I'm unfamiliar with the __new__ protocol.

__new__ is called to create a new instance of the class.  It is a 
staticmethod that gets passed as its first parameter the class to be 
created.  You should be able to do something like[1]:

py> import decimal
py> class MyDecimal(decimal.Decimal):
...     def __new__(cls, value):
...         if isinstance(value, float):
...             value = str(value)
...         return super(MyDecimal, cls).__new__(cls, value)
...
py> MyDecimal(3.0)
Decimal("3.0")

STeVe

[1] If you're really afraid of super for some reason, you can replace 
the line:
     return super(MyDecimal, cls).__new__(cls, value)
with
     return decimal.Decimal.__new__(cls, value)



More information about the Python-list mailing list