Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > list modification subclassing

Reply
Thread Tools

list modification subclassing

 
 
manstey
Guest
Posts: n/a
 
      05-21-2007
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

 
Reply With Quote
 
 
 
 
AchatesAVC
Guest
Posts: n/a
 
      05-21-2007
On May 20, 8:55 pm, manstey <mans...@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.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
in place list modification necessary? What's a better idiom? MooMaster Python 11 04-09-2009 05:09 AM
TypeError when subclassing 'list' Gerard Flanagan Python 5 02-27-2006 11:37 AM
subclassing list spike Python 4 08-01-2005 02:03 AM
subclassing list Uwe Mayer Python 2 12-23-2004 02:48 PM
JSTL el list subclassing and property conflicts Usenet Poster!!! Java 0 09-21-2004 02:01 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57