subclassing Decimal

J

jbauer

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.

Jeff Bauer
Rubicon, Inc.
 
S

Steven Bethard

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)
 
J

jbauer

STeVe,

Thanks for the response. Very clear.

yea-though-I-walk-thru-the-valley-of-__new__-I-will-fear-no-super-ly
y'rs,

-Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,221
Messages
2,571,131
Members
47,747
Latest member
swapote

Latest Threads

Top