subclassing int and accessing the value
Mark McEahern
marklists at mceahern.com
Mon Jul 8 16:10:21 EDT 2002
> 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
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.
Cheers,
// mark
-
More information about the Python-list
mailing list