subclassing int and accessing the value
Dave Reed
dreed at capital.edu
Mon Jul 8 16:23:43 EDT 2002
> From: "Mark McEahern" <marklists at mceahern.com>
> Date: Mon, 8 Jul 2002 15:10:21 -0500
> Content-Type: text/plain;
> charset="iso-8859-1"
> X-Priority: 3 (Normal)
> X-MSMail-Priority: Normal
> Importance: Normal
> X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000
> Content-Length: 609
>
> > Now my question is, how do I access the actual value 5 internally so I
> > can write my own __repr__ method that returns '$0.05'. I'm guessing it's
> > using __getattribute__, but what attribute do I want to access?
>
> Short answer: Look no farther than self. ;-)
>
> E.g.,
>
> class money(int):
>
> def __init__(self, *args):
> super(int, self).__init__(*args)
>
> def __str__(self):
> return "$%1.2f" % (float(self) / 100)
>
> x = money(5)
>
> print x
Ugh, that's too simple :-) Thanks!
Is there a long answer? :-)
> If you're looking for a way to represent money, you may want to use a fixed
> decimal class. I'm using Tim Peter's FixedPoint class.
Yes, I need to give this some more thought. If I actually end up using
this, it will need to interface with a database (MySQL or PostgreSQL)
so I need something that will be easy to back and forth between the
SQL representation and the Python representation.
I got your reply before I even saw my message show up on the list - I
must be near the bottom of the send list.
Thanks,
Dave
More information about the Python-list
mailing list