Subclassing types and __init__ problems

Alex Martelli aleax at aleax.it
Tue Mar 25 11:24:18 EST 2003


Lucio Torre wrote:

> Hello all,
> 
> I have subclassed int and i am having some problems.
> 
> Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> class myclass(int):
> ...     def __init__(self, param):
> ...             print param
> ...
>  >>> i = myclass(1)
> 1
>  >>> i = myclass([1,2,3])
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> TypeError: int() argument must be a string or a number
>  >>>
> 
> I imagine this is an issue with the types/class unification and stuff.

Well, "and stuff", yes.  It's __new__ that's giving you the problem,
though.  You aren't overriding it, so int.__new__ runs, and it doesn't
know what to do with a list argument!

> My questions are:
> is the previous code supposed to call int.__init__?
> how can i make a class so that isinstance(myclass, int) is 1, but im not

I assume you mean issubclass -- using int as a metaclass is not viable.

>    forced to call int.__init__?

Override __new__ and do whatever you wish.  E.g.:

>>> class myc(int):
...   def __new__(cls, param):
...     print param
...     return int.__new__(cls)
...
>>> i = myc(1)
1
>>> i
0
>>>

Note that "seen as an int", i has been generated without parameters,
so it's 0 -- and that's the value used by __repr__, as we haven't
overridden THAT.


Alex





More information about the Python-list mailing list