__new__ woes with list

Discussion in 'Python' started by macaronikazoo, Nov 21, 2008.

  1. 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 )
     
    macaronikazoo, Nov 21, 2008
    #1
    1. Advertisements

  2. 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).
     
    Arnaud Delobelle, Nov 21, 2008
    #2
    1. Advertisements

  3. ok thansk - i will search again. i did try searching but didn't find
    anything relevant...
     
    macaronikazoo, Nov 21, 2008
    #3
  4. Arnaud Delobelle, Nov 21, 2008
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.