list modification subclassing

M

manstey

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
 
A

AchatesAVC

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.
 

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

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top