iterating over a derived list

Donnal Walter donnal at donnal.net
Mon May 6 13:19:43 EDT 2002


In the code snippet below, I have derived a class from the built-in
type "list" to implement 'type checking' for objects placed in the
list and serialization of the list to and from an XML file. I also
want to be able to iterate over the retrieved list using Prev() and
Next(). My question is this: is there a more efficient way to
implement this behavior than the methods below (or some built-in way
to do this)?

Donnal Walter
Arkansas Children's Hospital

======= 
class ElementList(list):
    def __init__(self):
        list.__init__(self)
        # ... additional private attributes here
        self.__index = 0

    def Append(self, object):
        """Append object to the list with 'type checking'."""
        # ... implementation code here

    def Store(self, writer):
        """Store serialized content to designated xmlWriter."""
        # ... implementation code here

    def Retrieve(self, reader):
        """Retrieve serialized data from designated xmlReader."""
        # ... implementation code here

    def Reinit(self):
        del self[0:]        # empty the list
        self.__index = 0

    def Prev(self):
        """Return the previous element in the list."""
        if self.__index > 1:
            self.__index += -1
            return self[self.__index - 1]
        else: return None

    def Next(self):
        """Return the next element in the list."""
        if self.__index < len(self):
            self.__index += 1
            return self[self.__index - 1]
        else: return None



More information about the Python-list mailing list