__new__ woes with list

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • macaronikazoo

    __new__ woes with list

    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 convertDataToLi st( data ): return [1,2,3]
    class TMP(list):
    def __new__( cls, data ):
    if isinstance(data , basestring):
    new = convertDataToLi st( data )
    return list.__new__( cls, new )

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

    #2
    Re: __new__ woes with list

    macaronikazoo <macaronikazoo@ gmail.comwrites :
    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 convertDataToLi st( data ): return [1,2,3]
    class TMP(list):
    def __new__( cls, data ):
    if isinstance(data , basestring):
    new = convertDataToLi st( 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).

    --
    Arnaud

    Comment

    • macaronikazoo

      #3
      Re: __new__ woes with list



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

      Comment

      • Arnaud Delobelle

        #4
        Re: __new__ woes with list

        macaronikazoo <macaronikazoo@ gmail.comwrites :
        ok thansk - i will search again. i did try searching but didn't find
        anything relevant...
        Here's a link to the thread on google groups:



        Unfortunately two threads seem to be intertwined: scroll down to when
        the thread is renamed "python bug when subclassing list?".

        HTH

        --
        Arnaud

        Comment

        Working...