By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,071 Members | 1,244 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,071 IT Pros & Developers. It's quick & easy.

subclassing Decimal

P: n/a
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.

Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
jb****@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)
Jul 18 '05 #2

P: n/a
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

Jul 18 '05 #3

P: n/a
jb****@rubic.com wrote:
yea-though-I-walk-thru-the-valley-of-__new__-I-will-fear-no-super-ly


That's beautiful }:>

Cheers,
Nick.

--
Nick Coghlan | nc******@email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.