subclassing int and accessing the value

Tim Peters tim.one at comcast.net
Mon Jul 8 16:18:16 EDT 2002


[Dave Reed]
> 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.
> ...
> 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

Because ints are immutable, it's too late to affect what's stored in them by
the time __init__ is called (the "int part" of the memory has already been
initialized by the time __init__ is called, and can't be changed).  So the
__init__ method there has no effect.  This works just as well as the above:

class myint(int):
    pass

If you do want to affect what's stored in "the int part", you need to use
the __new__ method instead.

> 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?

It's simpler than that:  use self!  For example,

"""
class myint(int):
    def __str__(self):
        return "$%.2f" % (self / 1e2)

print myint(513)
"""

prints $5.13.

> 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.

The standard test Lib/test/test_descr.py has many examples of obscure
things.  Its inherits() function tests examples of subclassing from, e.g.,
long and complex.  Note that subclassing of builtin types is intended to be
used to add new behaviors and/or attributes; trying to override standard
behaviors is something of a crapshoot.






More information about the Python-list mailing list