Overriding list.__new__

Michele Simionato mis6 at pitt.edu
Sat Jul 5 08:41:31 EDT 2003


"Terry Reedy" <tjreedy at udel.edu> wrote in message news:<ULmcnd8rx5QlOJmiXTWJlg at comcast.com>...
> "Michele Simionato" <mis6 at pitt.edu> wrote in message
> news:2259b0e2.0307031246.6054693d at posting.google.com...
> > Let me show first how does it work for tuples:
> >
> > >>> class MyTuple(tuple):
> > ...     def __new__(cls,strng): # implicit conversion string of ints
>  => tuple
> > ...         return
>  super(MyTuple,cls).__new__(cls,map(int,strng.split()))
> > >>> MyTuple('1 2')
> > (1, 2)
> >
> > No wonder here, everything is fine. However, if I do the same for
> > lists I get the following:
> 
> Values of immutable objects must be set when created, because they
> cannot be changed thereafter.  Mutable objects can be initialized in
> the __init__() method.  I suspect this is true of lists, so that
> overriding __new__ for lists has no effect.
> 
> TJR

This seems reasonable now that you point it out to me.
Let me check ...

>>> class MyList(list):
	def __init__(self,strng):
		self.extend(list(map(int,strng.split())))

		
>>> MyList('1 2')
[1, 2]

It works, indeed!


                       Michele




More information about the Python-list mailing list