Overriding list.__new__

  • Thread starter Michele Simionato
  • Start date
M

Michele Simionato

Let me show first how does it work for tuples:
.... def __new__(cls,strng): # implicit conversion string of ints => tuple
.... return super(MyTuple,cls).__new__(cls,map(int,strng.split()))(1, 2)

No wonder here, everything is fine. However, if I do the same for
lists I get the following:
.... def __new__(cls,strng): #implicit conversion string of ints => tuple
.... return super(MyList,cls).__new__(cls,map(int,strng.split()))['1', ' ', '2']

The same is true for
.... def __new__(cls,strng):
.... return list.__new__(cls,map(int,strng.split()))['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:
.... def __new__(cls,strng):
.... return list.__new__(cls,map(int,[]) # !notice: empty list here!['1', ' ', '2']

In other words I always get the result of
['1', ' ', '2']

and it seems impossible to override list.__new__.

I am very puzzled about that; any suggestions?

Michele
 
T

Terry Reedy

Michele Simionato said:
Let me show first how does it work for tuples:

... def __new__(cls,strng): # implicit conversion string of ints => tuple
... return super(MyTuple,cls).__new__(cls,map(int,strng.split()))
(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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top