Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Overriding list.__new__ (http://www.velocityreviews.com/forums/t319212-overriding-list-__new__.html)

Michele Simionato 07-03-2003 08:46 PM

Overriding list.__new__
 
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:

>>> class MyList(list):

.... def __new__(cls,strng): #implicit conversion string of ints => tuple
.... return super(MyList,cls).__new__(cls,map(int,strng.split( )))
>>> MyList('1 2')

['1', ' ', '2']

The same is true for

>>> class MyList(list):

.... def __new__(cls,strng):
.... return list.__new__(cls,map(int,strng.split()))
>>> MyList('1 2')

['1', ' ', '2']

therefore it is not a problem of super.
The 'map' expression does not seem to be executed or, if its executed,
it has no effect at all. If I replace 'map' with anything, still I have
the same result:

>>> class MyList(list):

.... def __new__(cls,strng):
.... return list.__new__(cls,map(int,[]) # !notice: empty list here!
>>> MyList('1 2')

['1', ' ', '2']

In other words I always get the result of

>>> list('1 2')

['1', ' ', '2']

and it seems impossible to override list.__new__.

I am very puzzled about that; any suggestions?

Michele

Terry Reedy 07-03-2003 09:52 PM

Re: Overriding list.__new__
 

"Michele Simionato" <mis6@pitt.edu> wrote in message
news:2259b0e2.0307031246.6054693d@posting.google.c om...
> 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




All times are GMT. The time now is 09:27 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.