# Inheriting from int or long

Diez B. Roggisch deets at nospam.web.de
Tue Oct 2 15:16:14 CEST 2007

``` snorble at hotmail.com wrote:

> I started creating a simple "bits" class, intended to act like a array
> of bits. This was my initial idea, basically just overriding the
> string representation to display the bitmask (so far):
>
> class bits(long):
>     def __str__ (self):
>         s = ''
>         if self == 0L:
>             s += '-'
>         else:
>             x = self
>             while x >= 1:
>                 if x & 1L: s = '#' + s
>                 else:      s = '-' + s
>                 x >>= 1
>         return s
>
> My thought was this will act like a Long, and so should act like an
> array of bits with arbitrary precision, supporting the standard
> bitwise operations, along with others I may add.
>
>>>> import bits
>>>> b = bits.bits(32)
>>>> b
> 32L
>>>> print b
> #-----
>>>> b = bits.bits(35)
>>>> print b
> #---##
>>>> b = bits.bits(36)
>>>> print b
> #--#--
>>>> b <<= 1
>>>> print b
> 72
>
> So obviously when I attempt a bitwise operation (ex. b <<= 1), b is
> being assigned the result of b << 1, which is a Long.
>
>>>> b = bits.bits(36)
>>>> type(b)
> <class 'bits.bits'>
>>>> type (b << 1)
> <type 'long'>
>
> Is there any way around this without reimplementing all of the bitwise
> operators? It's not the biggest deal to reimplement the operators, but
> it kind of defeats the benefit of inheriting from an integer type.

No, there isn't. How is the existing operation of the operator going to know
that you want an instance of bits instead of long? It can't possibly know
that, even if it looked at the class of one or even both of it's operands:
it could be that instantiating a bits-object needed a reference to
TheCommonApplicationContextThingy or so....

> If there isn't a way around this, then I am curious in what situations
> it would be beneficial to inherit from an int or long. This issue
> seems more related to numeric types, since they are so centered around
> operations that involve assignment, as opposed to, say, a List, which
> has some operators (ex. +=), but does not depend on them (ex. use