Subclass of int and initialisation with not integer values

Boris Boutillier boris.boutillier at lip6.fr
Wed Apr 24 12:26:30 EDT 2002


On Wed, 24 Apr 2002 17:09:53 +0200, Boris Boutillier wrote:

> Hi all,
> 
> I've got a little problem with subclass of int.
> 
> Here is a sample of what I want to do :
> 
> class toto(int):
> 	true  = 'O'
> 	false = 'N'
> 	def __init__(self,str):
> 		self.str = str
> 		if str=='O':
> 			int.__init__(self,1)
> 		elif str == 'N':
> 			int.__init__(self,0)
> 		else:
> 			raise ValueError, 'Not valid value %s'%(str)
> 	def __str__(self):
> 		return self.str
>>>> x = toto('N')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): N
>>>> x = toto(1)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 11, in __init__
> ValueError: Not valid value 1
> 
> In some way it seems that the int initialisation is called before
> __init__ I want toto to be a subclass of int because I need toto objects
> to be used as index for lists.
> 
> Do you know some way to solve the problem ? Here true and false are 'O'
> and 'N' for the example but in my example I use a metaclass to create
> numerous classes of this kind, with different true letter and false
> letter.
> 
> Boris
> .

In fact I found the answer, it is that __new__ is called before __init__
and as a true int is return by new, __init__ is called too late.
So i solved my problem by redefining __new__ instead of __init__.

Sorry for this useless post.

Boris Boutillier



More information about the Python-list mailing list