list modification subclassing

AchatesAVC AchatesAVC at gmail.com
Sun May 20 21:54:05 EDT 2007


On May 20, 8:55 pm, manstey <mans... at csu.edu.au> 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.




More information about the Python-list mailing list