Accessing 'mangled' class attrbutes

Gerard Flanagan grflanagan at yahoo.co.uk
Wed Mar 1 18:50:31 CET 2006


Steve Juranich wrote:
> Gerard Flanagan wrote:
>
> > I would like to do the following:
> >
> >   from elementtree.SimpleXMLWriter import XMLWriter
> >
> >   class HtmlWriter(XMLWriter, object):
> >       def write_raw(self, text):
> >           super( HtmlWriter, self ).flush()
> >           super( HtmlWriter, self ).__write(text)
> >
> > but because of the name-mangling caused by '__write' I get:
> >
> > AttributeError: 'super' object has no attribute '_HtmlWriter__write'.
> >
> > Is there any simple way round this situation in general?
> >
> > (I just want to write out a HTML 'DOCTYPE' declaration)
>
> Try: (not the Python keyword, but a directive to you)
>
> super(HtmlWriter, self)._XMLWriter__write(text)
>
> In general, to access the name-mangled members, simply add
> _<class_name> to the front of the member name and you should be able to get
> at it.  But be careful, since this is a reference to the base class, so if
> it's inherited from some other class, you'll need to know from which class
> the member is inherited.
>
> HTH
>
> --
> Steve Juranich
> Tucson, AZ
> USA

I tried that Steve but it didn't work, and i don't think I can do what
I want in any case.  There is no method '__write' in the base class, it
is only declared as an instance attribute in the constructor, like so:

    def __init__(self, file, encoding="us-ascii"):
        ...
        self.__write = file.write
        ...

I tried putting  '__write = None' at the class level (in the base class
XMLWriter) but then, although '_XMLWriter__write' appears in
'dir(HtmlWriter)', I get  'NoneType is not callable'.

I also tried 'def __write(self, text) : pass ' in the base class, but
then the code runs but doesn't write the text I want -  and anyway, if
I'm going to change the base class, then i may as well just add the
'write_raw' method to the base directly!

It's just some toy code at any rate, and I've learnt something new!
Thanks for your reply.

Gerard




More information about the Python-list mailing list