list modification subclassing

Discussion in 'Python' started by manstey, May 21, 2007.

  1. manstey

    manstey Guest

    Hi,

    I have a simple subclass of a list:

    class CaListOfObj(list):
    """ subclass of list """
    def __init__(self, *args, **kwargs):
    list.__init__(self, *args, **kwargs)

    a= CaListOfObj([1,2,3])

    How do I write a method that does something EVERY time a is modified?

    Thanks
     
    manstey, May 21, 2007
    #1
    1. Advertising

  2. manstey

    AchatesAVC Guest

    On May 20, 8:55 pm, manstey <> wrote:
    > Hi,
    >
    > I have a simple subclass of a list:
    >
    > class CaListOfObj(list):
    > """ subclass of list """
    > def __init__(self, *args, **kwargs):
    > list.__init__(self, *args, **kwargs)
    >
    > a= CaListOfObj([1,2,3])
    >
    > How do I write a method that does something EVERY time a is modified?
    >
    > Thanks



    You could overridge the __setitem__ and __setslice__ methods like so.

    def somefunc():
    print 'Hello There'

    class CaListOfObj(list):
    """ subclass of list """
    def __init__(self, *args, **kwargs):
    list.__init__(self, *args, **kwargs)
    def __setitem__(self,i,y):
    list.__setitem__(self,i,y)
    somefunc()
    def __setslice__(self,i,j,y):
    list.__setslice__(self,i,j,y)
    somefunc()

    >>> a= CaListOfObj([1,2,3])
    >>> a[0]=2

    Hello There
    >>> a[1:2]=[4,5]

    Hello There

    Is that anything like what you're trying to do? If you want this to
    work with append and extend you'll have to do the same sort of thing
    with those.
     
    AchatesAVC, May 21, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Usenet Poster!!!
    Replies:
    0
    Views:
    3,019
    Usenet Poster!!!
    Sep 21, 2004
  2. spike

    subclassing list

    spike, Aug 1, 2005, in forum: Python
    Replies:
    4
    Views:
    3,991
    Robert Kern
    Aug 1, 2005
  3. Gerard Flanagan

    TypeError when subclassing 'list'

    Gerard Flanagan, Feb 26, 2006, in forum: Python
    Replies:
    5
    Views:
    307
    Gerard Flanagan
    Feb 27, 2006
  4. manstey

    subclassing list question

    manstey, May 21, 2007, in forum: Python
    Replies:
    0
    Views:
    251
    manstey
    May 21, 2007
  5. MooMaster
    Replies:
    11
    Views:
    427
    MooMaster
    Apr 9, 2009
Loading...

Share This Page