By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,965 Members | 1,690 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,965 IT Pros & Developers. It's quick & easy.

list modification subclassing

P: n/a
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

May 21 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On May 20, 8:55 pm, manstey <mans...@csu.edu.auwrote:
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.

May 21 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.