instance as a sequence

Matimus mccredie at gmail.com
Mon Nov 5 14:26:50 EST 2007


On Nov 5, 9:59 am, snd... at gmail.com wrote:
> On Nov 5, 9:40 am, Paul McGuire <pt... at austin.rr.com> wrote:
>
> > On Nov 5, 11:32 am, snd... at gmail.com wrote:
>
> > > suppose i want to
> > > make foo.childNodes[bar] available as foo[bar]
> > > (while still providing access to the printxml/printprettyxml()
> > > functions
> > > and other functionality of dom/minidom instance).
>
> > > What is a good way to accomplish that?
>
> > define __getitem__(self, index) method on foo's class, and have the
> > method return foo.childNodes[index].
>
> > If you don't have access to foo's class, then just do this:
>
> > foo.__getitem__ = delegatingGetItemMethod
>
> > and define delegatingGetItemMethod as described above.
>
> could i plug it into the (exiting) xml.dom.minidom class rather than
> the instance?

If you want that type of functionality it is better to just create a
new class, inherit from Document and use the new class.

class MyDocument(xml.dom.minidom.Document):
    def __getitem__(self, index):
      #blah ...

You could then do this: `xml.dom.minidom.Document = MyDocument', but
changing the Document class itself, especially for such a trivial
improvement is just confusing to whoever might be reading your code.
Like another poster said, if you want a more convenient way to modify
and read XML use ElementTree. minidom works the way it does because it
it following a W3C specification. If you start modifying it for
convenience you will 1. break the specification and 2. reinvent the
wheel because there already exists more convenient means of accessing
XML.


Matt




More information about the Python-list mailing list