Accessing 'mangled' class attrbutes

Steve Juranich sjuranic at gmail.com
Wed Mar 1 13:26:31 EST 2006


Gerard Flanagan wrote:

> 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
> 

Make sure you're calling the super's constructor before you try and access
the mangled member.  Then (I forgot this part), you can just call the
mangled member from `self'.  Example follows.

<foo.py>
class A(object):
    def __init__(self):
        self.__foo = lambda x, y : x + y

class B(A):
    def __init__(self, x, y):
        # Make sure you're calling the super's constructor first.
        super(B, self).__init__()
        self.sum = self._A__foo(x, y)
</foo.py>

>>> import foo
>>> b = foo.B(3, 4)
>>> b.sum
7
>>> 

-- 
Steve Juranich
Tucson, AZ
USA




More information about the Python-list mailing list