Sunday, April 17, 2011

Add event to list

I want to add event to list such that on adding items actions are taken based on the item e.g. genrating new data structures, change in screen output or raising exception.

How do I accomplish this?

From stackoverflow
  • You could create your own class that extends the list object:

    class myList(list):
        def myAppend(self, item):
            if isinstance(item, list):
                print 'Appending a list'
                self.append(item)
            elif isinstance(item, str):
                print 'Appending a string item'
                self.append(item)
            else:
                raise Exception
    
    L = myList()
    L.myAppend([1,2,3])
    L.myAppend('one two three')
    print L
    
    #Output:
    #Appending a list
    #Appending a string item
    #[[1, 2, 3], 'one two three']
    
    Jarret Hardie : +1... but no need to call the method "myAppend"... using the normal append method name is probably better, just call the superclass append to implement the actual appending

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.