Questions about subclassing an int

Arnaud Delobelle arnodel at googlemail.com
Fri Jan 4 18:36:27 EST 2008


On Jan 4, 10:55 pm, "Steven W. Orr" <ste... at syslang.net> wrote:
> class S(int):
>      def __init__(self, value):
>         self.value = value
>      def addStr(self, str):
>         self.doc = str
>
> s = S(44)
> s.addStr('Hello')
>
> print 's = ', s
> print 's.doc = ', s.doc
>
> class T(int):
>      def __init__(self, value, str):
>         self.value = value
>         self.doc = str
>
> t = T(44, 'Goodbye')
>
> print 't = ', t
> print 't.doc = ', t.doc
>
> It works ok with S but it fails when I try to instantiate T with a syntax
> error. Why?
>
> Also, I don't understand why S works. If I change the name of value and
> use something else, the print of s still works by printing the integer
> value out. How does it know what value to use? Also, in S.__init__, should
> I be calling super(S, self).__init__(value) or is there a difference?

I suggest you read http://www.python.org/download/releases/2.2.3/descrintro/

Briefly, S(44) calls first S.__new__(S, 44) which does not exist, so
falls back to int.__new__(S, 44) which creates the new object s which
is 44 as an integer. Then *only*, s.__init__(44) is called and your
code is executed.  Try changing self.value=value to self.value='SPAM',
you will see that 'print s' still returns 44.

As for T(44, 'Goodbye'), the same happens.  First T.__new__ does not
exist, so int.__new__(T, 44, 'Goodbye') is executed and this is where
the error comes from (shouldn't it be a TypeError?) as this means
"create the integer whose representation in base 'Goodbye' is 44".

As for calling int.__init__, there is no point: integers don't have an
__init__() since they are immutable.

> And just for fun:
>
> class R(int):
>      def __init__(self, value, doc):
>          super(R, self).__init__(value)
>          self.doc = doc
>
> r = R(66,'GGG')
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> TypeError: an integer is required
>
> Now it's no longer a syntax error but I don't see why it's different?

Same as above, though I don't understand why you get a SyntaxError for
T and a TypeError for R. AFAICT both shoult give a TypeError.

--
Arnaud




More information about the Python-list mailing list