instance as a sequence

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Nov 5 20:48:24 CET 2007


sndive at gmail.com a écrit :
> 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?

from xml.dom import minidom
minidom.Node.__getitem__ = lambda self, index: self.childNodes[index]
doc = minidom.parseString("<foo><bar/></foo>")
doc[0]
=> <DOM Element: foo at 0x407c322c>

But ElementTree might be a better choice still...







More information about the Python-list mailing list