__new__ woes with list

M

macaronikazoo

i'm having a hell of a time getting this to work. basically I want to
be able to instantiate an object using either a list, or a string, but
the class inherits from list.

if the class is instantiated with a string, then run a method over it
to tokenize it in a meaningful way.

so how come this doesn't work??? if I do this:

a=TMP( 'some string' )

it does nothing more than list('some string') and seems to be ignoring
the custom __new__ method.



def convertDataToList( data ): return [1,2,3]
class TMP(list):
def __new__( cls, data ):
if isinstance(data, basestring):
new = convertDataToList( data )
return list.__new__( cls, new )

if isinstance(data, list):
return list.__new__( cls, data )
 
A

Arnaud Delobelle

macaronikazoo said:
i'm having a hell of a time getting this to work. basically I want to
be able to instantiate an object using either a list, or a string, but
the class inherits from list.

if the class is instantiated with a string, then run a method over it
to tokenize it in a meaningful way.

so how come this doesn't work??? if I do this:

a=TMP( 'some string' )

it does nothing more than list('some string') and seems to be ignoring
the custom __new__ method.



def convertDataToList( data ): return [1,2,3]
class TMP(list):
def __new__( cls, data ):
if isinstance(data, basestring):
new = convertDataToList( data )
return list.__new__( cls, new )

if isinstance(data, list):
return list.__new__( cls, data )

A list is mutable, its initialisation is done in __init__() not
__new__(). There was a recent post about this (in the last couple of
weeks).
 
M

macaronikazoo

ok thansk - i will search again. i did try searching but didn't find
anything relevant...
 

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,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top