subclassing int and accessing the value

Dave Reed dreed at capital.edu
Mon Jul 8 15:36:28 EDT 2002


Let's say I want to subclass int to write my own class for handling
monetary values (i.e., represent them in cents, but print them in
dollars and cents, but otherwise allow normal addition, subtraction of
ints to work). For example, store 150, but print $1.50. First, I'm not
certain this is the best way to do it (and it probably isn't), but
it's really just a learning exercise for learning about subclassing
built-in types.

The following works so it appears to be possible.

class myint(int):
    def __init__(self, v):
        int.__init__(self, )

i = myint(5)
print i # prints 5



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?

I haven't found any examples for subclassing numeric types, only
dicts and lists at
http://www.python.org/2.2.1/descrintro.html#subclassing.

Thanks,
Dave






More information about the Python-list mailing list