simple integer subclass

Roald de Vries downaold at
Tue Aug 3 17:43:21 CEST 2010

Hi Andreas,

On Aug 3, 2010, at 1:52 AM, Andreas Pfrengle wrote:
> I'm trying to define a subclass of int called int1. An int1-object
> shall behave exactly like an int-object, with the only difference that
> the displayed value shall be value + 1 (it will be used to display
> array indices starting at 1 instead of 0). Right now I have:
> class int1(int):
>    def __str__(self):
>        return int.__str__(self + 1)
> However, if I calculate with int1 and int- (or other number) objects,
> the result is always coerced to an int (or other number object), e.g:
> a = int1(5)
> b = 5
> print a      # "6"
> print a+b  #"10"
> How can I tell int1 to be the "default integer object"? Do I need to
> overload *every* mathematical operation method of int, or is there an
> easier way?

Maybe you could use:
1) a dict with keys 1..n
2) a simple list (or iterable) subclass with 1-based indices.

     class list1(list):
         def __new__(cls, *args, **kwargs):
             return list.__new__(cls, *args, **kwargs)

         def __getitem__(self, key):
             return list.__getitem__(self, key-1)

         ... etcetera

Cheers, Roald

More information about the Python-list mailing list